首页 > 代码库 > Async

Async

1             Action act = () =>
2                     {
3                         Thread.Sleep(2500);
4                         Console.WriteLine("这里是委托调用的act内容 {0}", Thread.CurrentThread.ManagedThreadId);
5                         Thread.Sleep(2500);
6                     };

同步:

1           act.Invoke();
2                 //act();
3                 Console.WriteLine("第一次同步执行后{0}", Thread.CurrentThread.ManagedThreadId);

异步:

 1           IAsyncResult asyncResult1 = null; //表示异步操作的状态。
 2                 //在相应异步操作完成时调用的方法。public delegate void AsyncCallback(IAsyncResult ar);
 3                 AsyncCallback callback = houniao => //houniao代表IAsyncResult类型---根据它判断是否执行回调函数
 4                     {                    
 5                         Console.WriteLine(houniao.AsyncState);
 6                         Console.WriteLine("object.ReferenceEquals(asyncResult1,houniao)? {0}", object.ReferenceEquals(asyncResult1, houniao));
 7                         Console.WriteLine("这里是回调{0}", Thread.CurrentThread.ManagedThreadId);
 8                     };
 9                                                            //回掉函数 //object AsyncState { get; }用户定义的对象,它限定或包含关于异步操作的信息。
10                 IAsyncResult asyncResult = act.BeginInvoke(callback, "闪闪发光的台湾手抓饼");//异步执行
11                 asyncResult1 = asyncResult;

 

异步等待:

不带参数

 1                int i = 0;
 2                 Console.WriteLine("开始上传。。。");
 3                 while (!asyncResult.IsCompleted)
 4                 {
 5                     Console.WriteLine("已经完成上传{0}%", i++ * 5);
 6                     Thread.Sleep(200);
 7                 }
 8 
 9                 asyncResult.AsyncWaitHandle.WaitOne(1000);//获取用于等待异步操作完成的 System.Threading.WaitHandle并设置间隔时间
10          或者
11                 act.EndInvoke(asyncResult);
12 
13                 Console.WriteLine("上传成功。。。");
14 
15 
16                 Console.WriteLine("第一次异步执行后{0}", Thread.CurrentThread.ManagedThreadId);    

 

带参数(有没有参数看委托)

 1       {
 2                 Func<string, string> func = t => string.Format("{0} {1}", t, DateTime.Now.ToString());
 3                 string result1 = func.Invoke("zhaotx(89-zhaotx-男-成都)");
 4                 Console.WriteLine(result1);
 5 
 6 
 7                 IAsyncResult asyncResult = func.BeginInvoke("KOBE→Bryant",
 8                    t =>
 9                    {
10                        //string result3 = func.EndInvoke(t);//只能EndInvoke一次
11                        Console.WriteLine("这里是回调{0}", Thread.CurrentThread.ManagedThreadId);
12                    }, null);
13 
14                 string result2 = func.EndInvoke(asyncResult);
15                 Console.WriteLine(result2);
16             }

 

Async