public bool Invoke(int duration, object sender, EventArgs e) { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; IAsyncResult result = handler.BeginInvoke(sender, e, null, null);// obj.BeginInvoke(token, null, null); new Thread(() => { Thread.Sleep(duration); if (result.IsCompleted != true) { token.ThrowIfCancellationRequested(); } }).Start(); try { obj.EndInvoke(result); Console.WriteLine("\nOperation finished successfully."); return(true); } catch (OperationCanceledException) { Console.WriteLine("\nOperation was canceled."); return(false); } }
static void Main(string[] args) { int result; //往委托列表中添加方法 MyDelegate d = Add; //调用BeginInvoke 方法用于启动异步调用 Console.WriteLine("异步调用MyDelegate 开始"); //接受异步调用后的结果 IAsyncResult iar = d.BeginInvoke(123, 456, out result, null, null); //循环模拟其他操作,每隔500MS打一个 . 号 for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.Write("."); } Console.WriteLine("等待"); //使用IAsyncResult.AsyncWaitHandle获取WaitHandle //使用WaitOne方法执行 阻塞等待 //异步调用完成时会发出WaitHandle信号,可通过WaitOne等待 iar.AsyncWaitHandle.WaitOne(); Console.WriteLine("异步调用 Add()方法"); //使用EndInvoke方法检索异步调用结果 //EndInvoke方法:若异步调用未完成,EndInvoke将阻塞到异步调用完成 d.EndInvoke(out result, iar); //等待调用完成,输出结果 Console.WriteLine("异步调用 Add结果:{0}", result); }
public static void MyCallBack(IAsyncResult ar) { MyDelegate d = (MyDelegate)((AsyncResult)ar).AsyncDelegate; d.EndInvoke(ar); //Console.WriteLine( "Ola" + ); }
private void button1_Click(object sender, EventArgs e) { //Task t = DoSomethingAsync(); //Task t = new Task(Test); //t.Start(); button1.Enabled = false; MyDelegate myDel = AsyncMethod; IAsyncResult rs = myDel.BeginInvoke(10000, null, null); while (!rs.IsCompleted) { //label1.Text = "..."; //Thread.Sleep(10); } string res = myDel.EndInvoke(rs); label1.Text = res; BeginInvoke(new MethodInvoker(delegate() { button1.Enabled = true; })); }
static void Main(string[] args) { int result; MyDelegate d = Add;//创建委托实例 //调用BeginInvoke方法用于启动异步调用 Console.WriteLine("委托异步调用方法开始:"); IAsyncResult iar = d.BeginInvoke(123, 456, out result, null, null); Console.Write("执行其他操作"); for (int i = 0; i < 10; i++) { Thread.Sleep(500); Console.Write("."); } Console.WriteLine("等待"); //使用IAsyncResult.AsyncWaitHandle获取WaitHandle,使用WaitOne方法执行 //阻塞等待,异步完成之时会发出WaitHandle信号,可通过WaitOne等待 iar.AsyncWaitHandle.WaitOne(); Console.WriteLine("异步调用AsyncDelegate.Add()方法结束"); //EndInvoke方法:若异步调用未完成,EndInvoke将一直阻塞到异步调用完成 d.EndInvoke(out result, iar); Console.WriteLine("异步调用异步调用AsyncDelegate.Add()方法结果:{0}", result); Console.ReadKey(); }
static void Main(string[] args) { MyDelegate d = Square; System.Console.WriteLine("Thread-Id: {0}", Thread.CurrentThread.ManagedThreadId); IAsyncResult iar = d.BeginInvoke(12, null, null); while (!iar.IsCompleted) { System.Console.WriteLine("Blabla"); } int result = d.EndInvoke(iar); System.Console.WriteLine(result); // Process[] processList = Process.GetProcesses("."); // foreach(Process process in processList){ // System.Console.WriteLine("PID: {0}, Process-name: {1}", process.Id, process.ProcessName); // } // Process cal = Process.Start("cal"); // Thread.Sleep(5000); // cal.Kill(); }
public void 基础() { //建立委托 MyDelegate myDelegate = new MyDelegate(Hello); //异步调用委托,获取计算结果 IAsyncResult result = myDelegate.BeginInvoke("Leslie", null, null); //在异步线程未完成前执行其他工作 while (!result.IsCompleted) { Thread.Sleep(200); //虚拟操作 Console.WriteLine("Main thead do work!"); } //也可以使用WailHandle完成同样的工作,WaitHandle里面包含有方法WaitOne,与使用 IAsyncResult.IsCompleted 同样且更方便 while (!result.AsyncWaitHandle.WaitOne(200)) { Console.WriteLine("Main thead do work!"); } //等待异步方法完成,调用EndInvoke(IAsyncResult)获取运行结果 string data = myDelegate.EndInvoke(result); // EndInvoke执行完毕,取得之前传递的参数内容 string strState = (string)result.AsyncState; Console.WriteLine(data); }
private void Btn_Start_Click(object sender, EventArgs e) { MyDelegate myDelegate = new MyDelegate((string para) => { System.Diagnostics.Trace.WriteLine("delegate thread:" + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(3000); return(para.Length); }); IAsyncResult result = myDelegate.BeginInvoke("Leslie", null, null); System.Diagnostics.Trace.WriteLine("start invoke"); using (WebClient wc = new WebClient()) { Tb_ThreadInfo.Text = wc.DownloadString(new Uri("http://www.cnblogs.com")); System.Diagnostics.Trace.WriteLine("download ok:" + Tb_ThreadInfo.Text.Length); } System.Diagnostics.Trace.WriteLine("main thread:" + Thread.CurrentThread.ManagedThreadId); int data = myDelegate.EndInvoke(result); System.Diagnostics.Trace.WriteLine("result:" + data.ToString()); }
static void Main(string[] args) { MyDelegate myFun = TaskWhile; IAsyncResult result = myFun.BeginInvoke(1, 3000, null, null); while (!result.IsCompleted) { Console.Write("."); Thread.Sleep(50); } int i = myFun.EndInvoke(result); Console.WriteLine("异步委托返回结果是:{0}", i); MyDelegate myFun1 = TaskWhile; IAsyncResult result1 = myFun1.BeginInvoke(1, 2000, null, null); while (!result1.IsCompleted) { Console.Write("."); Thread.Sleep(50); } int j = myFun1.EndInvoke(result1); Console.WriteLine("异步委托返回结果是:{0}", j); }
//【5】创建回调函数 private void MyCallback(IAsyncResult result) { int res = objCal.EndInvoke(result); //异步显示结果 Console.WriteLine("第{0}个计算结果:{1}", result.AsyncState, res); }
private void button1_Click(object sender, EventArgs e) { MyDelegate add = new MyDelegate(Add); IAsyncResult addResult = add.BeginInvoke(5, 10, null, null); int result = add.EndInvoke(addResult); MessageBox.Show("5 + 10 = " + result); }
static void AsyncMethodComplete(IAsyncResult iar) { Console.WriteLine("Aszinkron szál kész..."); AsyncResult result = (AsyncResult)iar; MyDelegate d = (MyDelegate)result.AsyncDelegate; Console.WriteLine("Üzenet: {0}", iar.AsyncState); Console.WriteLine("Eredmény: {0}", d.EndInvoke(iar)); }
static void Main(string[] args) { MyDelegate mydelegate = new MyDelegate(TestMethod); IAsyncResult result = mydelegate.BeginInvoke("abcdefg", TestCallBack, "hijklmn"); string resultstr = mydelegate.EndInvoke(result); Console.WriteLine(resultstr); Console.ReadKey(); }
static void ThreadProc(IAsyncResult stateInfo) { MyDelegate delegat = ((object[])(stateInfo.AsyncState))[0] as MyDelegate; string info = ((object[])(stateInfo.AsyncState))[1] as string; AutoResetEvent ev = ((object[])(stateInfo.AsyncState))[2] as AutoResetEvent; Console.WriteLine(info + ": " + delegat.EndInvoke(stateInfo).ToString()); ev.Set(); }
static void Main(string[] args) { MyDelegate my = new MyDelegate(Add); AsyncCallback callback = new AsyncCallback(AddCompletion); IAsyncResult result = my.BeginInvoke(10, 20, callback, "qwerty"); int res = my.EndInvoke(result); Console.WriteLine("10 + 20 = " + res); Thread.Sleep(1000); }
static void Main(string[] args) { MyDelegate mydelegate = new MyDelegate(TestdelMethod); IAsyncResult res = mydelegate.BeginInvoke("Thread param", TestCallBack, "callback param"); string resstr = mydelegate.EndInvoke(res); Console.WriteLine(resstr); Console.ReadKey(); }
public void CommandCallBack(IAsyncResult ar) { // this is called when your task is complete AsyncResult asyncResult = (AsyncResult)ar; MyDelegate myDel = (MyDelegate)asyncResult.AsyncDelegate; WorkerClass command = myDel.EndInvoke(ar); // command is a reference to the original class that envoked the async call // m_test will equal "Hi" // m_test2 will equal "Later"; }
//执行完异步回调函数 public static void TestCallback(IAsyncResult data) { Console.WriteLine("Callback: {0}", num); AsyncResult ar = (AsyncResult)data; MyDelegate del = (MyDelegate)ar.AsyncDelegate; String res = del.EndInvoke(data); Console.WriteLine("{0}, result is {1}", ar.AsyncState, res); }
private void button4_Click(object sender, EventArgs e) { MyDelegate dele = new MyDelegate(TestMethod); //第一个参数回调成功后的结果,第二个参数执行的回调函数 IAsyncResult result = dele.BeginInvoke("Thread PARMA", AsyncResult, "CallBACK PARAM"); //异步完成结果 string str = dele.EndInvoke(result); MessageBox.Show(str); }
static void Completed(IAsyncResult result) { ThreadMessage("Async Completed"); AsyncResult _result = (AsyncResult)result; MyDelegate myDelegate = (MyDelegate)_result.AsyncDelegate; //获取委托对象,调用EndInvoke方法获取运行结果 string data = myDelegate.EndInvoke(_result); Console.WriteLine(data); }
private void button2_Click(object sender, EventArgs e) { MyDelegate add = new MyDelegate(Add); IAsyncResult addResult = add.BeginInvoke(1, 6, null, null); if (addResult.IsCompleted) { int result = add.EndInvoke(addResult); MessageBox.Show("1 + 6 = " + result); } }
public static void MyCallBack(IAsyncResult ar) { //获取当前的异步执行结果 AsyncResult myResult = (AsyncResult)ar; //获取当前的委托对象 m1 MyDelegate mmm1 = (MyDelegate)myResult.AsyncDelegate; string data = mmm1.EndInvoke(myResult); Console.WriteLine(data); }
//供异步线程完成回调的方法 static void Completed(IAsyncResult result) { //获取委托对象,调用EndInvoke方法获取运行结果 AsyncResult _result = (AsyncResult)result; MyDelegate myDelegaate = (MyDelegate)_result.AsyncDelegate; //获得参数 string data = myDelegaate.EndInvoke(_result); Console.WriteLine(data); //异步线程执行完毕 Console.WriteLine("异步线程完成咯!"); Console.WriteLine("回调函数也是由" + Thread.CurrentThread.Name + "调用的!"); }
//BeginInvoke() 除了最后两个参数,前面的都是你可定义的 /// <summary> /// 这种方法有一个缺点,就是不知道异步操作什么时候执行完,什么时候开始调用EndInvoke,因为一旦EndInvoke主线程就会处于阻塞等待状态。 /// </summary> public void Process() { //建立委托 MyDelegate myDelegate = new MyDelegate(GetString); //异步调用委托,除最后两个参数外,前面的参数都可以传进去 IAsyncResult result = myDelegate.BeginInvoke("张三", 22, null, null); Console.WriteLine($"主线程继续工作!,线程ID:{Thread.CurrentThread.ManagedThreadId}"); //调用EndInvoke(IAsyncResult)获取运行结果,一旦调用了EndInvoke,即使结果还没来得及返回,主线程也阻塞等待了 //注意获取返回值的方式 string data = myDelegate.EndInvoke(result); Console.WriteLine($"线程ID:{Thread.CurrentThread.ManagedThreadId},异步委托结果:{data}"); }
static void Main() { List <int> someInts = new List <int> { 1, 2, 3, 4, 5, 6, 7 }; MyDelegate test = FinalResult; test.BeginInvoke(someInts, ar => { MyDelegate del = (MyDelegate)ar.AsyncState; Console.WriteLine(del.EndInvoke(ar)); }, test); Console.ReadKey(true); }
//当要监视多个运行对象的时候,使用IAsyncResult.WaitHandle.WaitOne可就派不上用场了。 static void WaitAny用法(string[] args) { ThreadMessage("Main Thread"); //建立委托 MyDelegate myDelegate = new MyDelegate(Hello); //异步调用多个委托 IAsyncResult result1 = myDelegate.BeginInvoke("Leslie", null, null); IAsyncResult result2 = myDelegate.BeginInvoke("Leslie", null, null); //此处可加入多个检测对象 WaitHandle[] waitHandleList = new WaitHandle[] { result1.AsyncWaitHandle, result2.AsyncWaitHandle }; while (!WaitHandle.WaitAll(waitHandleList, 200)) { Console.WriteLine("Main thead do work!"); } string data1 = myDelegate.EndInvoke(result1); string data2 = myDelegate.EndInvoke(result2); Console.WriteLine(data1 + data2); Console.ReadKey(); }
static void Completed(IAsyncResult result) { ThreadMessage("Async Completed"); //获取委托对象,调用EndInvoke方法获取运行结果 AsyncResult _result = (AsyncResult)result; MyDelegate myDelegate = (MyDelegate)_result.AsyncDelegate; string data = myDelegate.EndInvoke(_result); //获取Person对象 Person person = (Person)result.AsyncState; string message = person.Name + "'s age is " + person.Age.ToString(); Console.WriteLine(data + "\n" + message); }
public static void Main(string[] args) { var d = new MyDelegate(Func); IAsyncResult result = d.BeginInvoke(10, null, null); while (!result.IsCompleted) { Console.WriteLine("Main Waiting"); Thread.Sleep(125); } string retval = d.EndInvoke(result); Console.WriteLine("Delegate call returned: {0}", retval); }
private void btnExecute2_Click(object sender, EventArgs e) { MyDelegate dete = ExecuteTask1; //异步操作执行状态借口 IAsyncResult result = dete.BeginInvoke(10, null, null); this.lblCount1.Text = "正在计算......"; this.lblCount2.Text = ExecuteTask2(10).ToString(); //EndInvoke方法借助IAsyncResult借口对象,不断地查询异步调用是否结束; //该方法知道异步调用的方法所有参数,所以异步调用完毕以后,取出异步调用结果作为返回值 int res = dete.EndInvoke(result); this.lblCount1.Text = res.ToString(); }
private void Completed(IAsyncResult result) { //获取委托对象,调用EndInvoke方法获取运行结果 AsyncResult _result = (AsyncResult)result; //此句是核心点 MyDelegate myDelegate = (MyDelegate)_result.AsyncDelegate; //获得参数 string data = myDelegate.EndInvoke(result); Console.WriteLine($"线程ID:{Thread.CurrentThread.ManagedThreadId},异步委托结果:{data}"); //异步线程执行完毕 Console.WriteLine("异步线程完成咯!"); Console.WriteLine("回调函数也是由[" + Thread.CurrentThread.Name + "]调用的!"); }
static void Main(string[] args) { MyDelegate asyncCall = new MyDelegate(Sum); Console.WriteLine("Starting method async."); IAsyncResult status = asyncCall.BeginInvoke(5, 6, null, null); Console.WriteLine("Async method is working"); Console.WriteLine("Calling EndInvoke()"); int result = asyncCall.EndInvoke(status); Console.WriteLine("EndInvoke() returned"); Console.WriteLine("Result={0}", result); }
public override void ShowUsage() { ThreadMessage("Main Thread"); //创建委托 MyDelegate myDelegate = new MyDelegate(Hello); //如果在使用myDelegate.BeginInvoke后立即调用myDelegate.EndInvoke,在异步线程未完成工作以前主线程将处于阻塞状态,等到异步线程结束获取计算结果后,主线程才能继续工作,这明显无法展示出多线程的优势。此时可以好好利用IAsyncResult 提高主线程的工作性能 Console.WriteLine("请选择使用何种方式发起异步线程未完成状态的判断?"); Console.WriteLine("1):轮询IsCompleted 2):WaitOne 3)WaiAll 4)回调函数"); //在异步线程未完成前执行其他工作 ConsoleKeyInfo key = Console.ReadKey(true); //记录开始任务时的时间 DateTime startWorkTime = DateTime.Now; if (key.Key == ConsoleKey.D1 || key.Key == ConsoleKey.D2 || key.Key == ConsoleKey.D3) { //异步调用委托,获取计算结果 IAsyncResult result = myDelegate.BeginInvoke("Frost", null, null); switch (key.Key) { #region 1、轮询result.IsCompleted属性 case ConsoleKey.D1: while (!result.IsCompleted) { Thread.Sleep(200); //虚拟操作 TimeSpan timeSpan = DateTime.Now - startWorkTime; Console.WriteLine("This is reported by main thread, async thread has done work for {0} ms.", timeSpan.TotalMilliseconds); } break; #endregion #region 2、WaitOne属性判断 //除此以外,也可以使用WailHandle完成同样的工作,WaitHandle里面包含有一个方法WaitOne(int timeout),它可以判断委托是否完成工作,在工作未完成前主线程可以继续其他工作。运行下面代码可得到与使用 IAsyncResult.IsCompleted 同样的结果,而且更简单方便 。 case ConsoleKey.D2: while (!result.AsyncWaitHandle.WaitOne(200)) { TimeSpan timeSpan = DateTime.Now - startWorkTime; Console.WriteLine("This is reported by main thread, async thread has done work for {0} ms.", timeSpan.TotalMilliseconds); } break; #endregion #region 3、WaitAll属性判断 //当要监视多个运行对象的时候,使用IAsyncResult.WaitHandle.WaitOne可就派不上用场了。 //幸好.NET为WaitHandle准备了另外两个静态方法:WaitAny(waitHandle[], int)与WaitAll (waitHandle[] , int)。 //其中WaitAll在等待所有waitHandle完成后再返回一个bool值。 //而WaitAny是等待其中一个waitHandle完成后就返回一个int,这个int是代表已完成waitHandle在waitHandle[]中的数组索引。 //下面就是使用WaitAll的例子,运行结果与使用 IAsyncResult.IsCompleted 相同。 //等待异步方法完成,调用EndInvoke获取运行结果 case ConsoleKey.D3: //加入所有检测对象 WaitHandle[] waitList = new WaitHandle[] { result.AsyncWaitHandle }; while (!WaitHandle.WaitAll(waitList, 200)) { TimeSpan timeSpan = DateTime.Now - startWorkTime; Console.WriteLine("Work has being doing for {0} ms.", timeSpan.TotalMilliseconds); } break; #endregion } string data = myDelegate.EndInvoke(result); Console.WriteLine(data); } else if (key.Key == ConsoleKey.D4) { #region 4、回调函数 //使用轮询方式来检测异步方法的状态非常麻烦,而且效率不高,有见及此,.NET为 IAsyncResult BeginInvoke(AsyncCallback , object)准备了一个回调函数。使用 AsyncCallback 就可以绑定一个方法作为回调函数,回调函数必须是带参数 IAsyncResult 且无返回值的方法: void AsycnCallbackMethod(IAsyncResult result) 。在BeginInvoke方法完成后,系统就会调用AsyncCallback所绑定的回调函数,最后回调函数中调用 XXX EndInvoke(IAsyncResult result) 就可以结束异步方法,它的返回值类型与委托的返回值一致。 //建立Person对象,用作参数 Person person = new Person(); person.Name = "Elva"; person.Age = 27; //第一个参数为委托方法对应的参数,第二个为回调函数,第三个为传入的参数 IAsyncResult result = myDelegate.BeginInvoke("Frost", new AsyncCallback(Completed), person); while (!result.IsCompleted) { Thread.Sleep(200); //虚拟操作 TimeSpan timeSpan = DateTime.Now - startWorkTime; Console.WriteLine("This is reported by main thread, async thread has done work for {0} ms.", timeSpan.TotalMilliseconds); } //可以看到,主线在调用BeginInvoke方法可以继续执行其他命令,而无需再等待了,这无疑比使用轮询方式判断异步方法是否完成更有优势。 //在异步方法执行完成后将会调用AsyncCallback所绑定的回调函数,注意一点,回调函数依然是在异步线程中执行,这样就不会影响主线程的运行,这也使用回调函数最值得青昧的地方。 //在回调函数中有一个既定的参数IAsyncResult,把IAsyncResult强制转换为AsyncResult后,就可以通过 AsyncResult.AsyncDelegate 获取原委托,再使用EndInvoke方法获取计算结果。 #endregion } Console.ReadKey(); }