C# 最简单的异步委托

View Code
//异步委托
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace AsyncDelete
{
    class Program
    {
        public delegate int TaskesAWhileDelegate(int data, int ms);
        static void Main(string[] args)
        {
            TaskesAWhileDelegate dl = TaskesAWhile;
            IAsyncResult ar = dl.BeginInvoke(1, 3000, null, null);
            Console.WriteLine("main主线程");
            while (!ar.IsCompleted)
            {
                Console.Write(".");
                Thread.Sleep(50);
            }
            
            int result = dl.EndInvoke(ar);
            Console.WriteLine("result:{0}", result);
            Console.Read();
        }
        static int TaskesAWhile(int data, int ms)
        {
            Console.WriteLine("TaskesAWhile started");
            Thread.Sleep(ms);
            Console.WriteLine("TaskesAWhile completed");
            return ++data;
        }
    }
}

或:

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 
 7 namespace AsyncDelete
 8 {
 9     class Program
10     {
11         public delegate int TaskesAWhileDelegate(int data, int ms);
12         static void Main(string[] args)
13         {
14             TaskesAWhileDelegate dl = TaskesAWhile;                
15             
16             IAsyncResult ar = dl.BeginInvoke(1, 300, new AsyncCallback(MyAsyncCallback), dl);
17             Console.WriteLine("main主线程");     
18             while (!ar.IsCompleted)
19             {
20                 Console.Write(".");
21                 Thread.Sleep(50);
22             }           
23            
24         }
25         static int TaskesAWhile(int data, int ms)
26         {
27             Console.WriteLine("TaskesAWhile started");
28             Thread.Sleep(ms);
29             Console.WriteLine("TaskesAWhile completed");
30             return ++data;
31         }
32 
33         static void MyAsyncCallback(IAsyncResult asyncResult)
34         {
35             Console.WriteLine("MyAsyncCallback start");
36             Thread.Sleep(30);
37             TaskesAWhileDelegate dll = asyncResult.AsyncState as TaskesAWhileDelegate;
38             Console.WriteLine("MyAsyncCallback:{0}", dll.EndInvoke(asyncResult));
39         
40 
41             Console.WriteLine("MyAsyncCallback completed");
42         }
43     }
44 }

 

//BegininInvoke()方法,返回类型:IAsyncResult

通过IAsyncResult获取委托执行的状态(IsCompleted)和调用委托EndInvoke()返回执行结果,

EndInvoke()方法会一直等待,直到委托完成其任务为止.

 

执行结果:

main主线程
TaskesAWhile started
.............................................................TaskesAWhile completed
result:2

posted @ 2012-12-10 23:41  bert.zeng  阅读(247)  评论(0)    收藏  举报