.net多线程 委托的异步调用

 1  Action<string> action = this.DoSomethingLong;
 2 
 3             IAsyncResult asyncResult = null;
 4 
 5             AsyncCallback callback = ia =>
 6             {
 7                 //Console.WriteLine(object.ReferenceEquals(asyncResult, ia));
 8                 //Console.WriteLine(ia.AsyncState);
 9                 //Console.WriteLine($"到这里计算已经完成了。{Thread.CurrentThread.ManagedThreadId.ToString("00")}。");
10             };
11             asyncResult = action.BeginInvoke("btnAsyncAdvanced_Click", callback, "hao");

1.beginInvoke 第一个参数:委托方法的参数

第二个参数:执行异步方法结束后回调方法,参数就是异步方法的返回值,

第三个参数:向回调方法里传入的参数

 1   int i = 0;
 2             while (!asyncResult.IsCompleted)//1 卡界面:主线程忙于等待
 3             {   //可以等待,边等待边做其他操作
 4                 //可能最多200ms的延迟
 5                 if (i < 10)
 6                 {
 7                     Console.WriteLine($"文件上传完成{i++ * 10}%..");//File.ReadSize
 8                 }
 9                 else
10                 {
11                     Console.WriteLine($"文件上传完成99.9%..");
12                 }
13                 Thread.Sleep(200);
14             }
15             Console.WriteLine($"上传成功了。。。..");

2.通过判断asyncResult.IsCompleted让主线程等待,但是会有最多200毫秒的延时,可能刚判断完子线程就执行完毕了.

1  asyncResult.AsyncWaitHandle.WaitOne();//等待任务的完成
2             asyncResult.AsyncWaitHandle.WaitOne(-1);//等待任务的完成
3             asyncResult.AsyncWaitHandle.WaitOne(1000);//等待;但是最多等待1000ms
4 
5             action.EndInvoke(asyncResult);//主线程等待传入的任务结束,可以获取委托的返回值

3.其他几种等待方法

 1  {
 2                 Func<int> func = () =>
 3                   {
 4                       Thread.Sleep(2000);
 5                       return DateTime.Now.Day;
 6                   };
 7                 Console.WriteLine($"func.Invoke()={func.Invoke()}");
 8 
 9                 IAsyncResult asyncResult = func.BeginInvoke(r =>
10                  {
11                      //func.EndInvoke(r); //拿到返回值干一些事情
12                      Console.WriteLine(r.AsyncState);
13                  }, "冰封的心");
14 
15                 Console.WriteLine($"func.EndInvoke(asyncResult)={func.EndInvoke(asyncResult)}");
16             }

4.endInvoke 获取返回值示例

 

posted on 2019-05-29 20:53  雯烈  阅读(608)  评论(0编辑  收藏  举报