异步编程练习

 1class Program
 2    {
 3        static void Main(string[] args)
 4        {
 5            //异步委托方法一
 6            Func<intint> func = new Func<intint>(Square);
 7            IAsyncResult ar1= func.BeginInvoke(10nullnull);
 8            while (!ar1.IsCompleted)
 9                Console.WriteLine(func.EndInvoke(ar1));
10
11            //异步委托方法二
12            IAsyncResult ar2 = func.BeginInvoke(20nullnull);
13            ar2.AsyncWaitHandle.WaitOne();
14            Console.WriteLine(func.EndInvoke(ar2));
15
16            //异步委托方法三
17            IAsyncResult ar3 = func.BeginInvoke(30,
18                result =>
19                {
20                    if (result.IsCompleted)
21                        Console.WriteLine(func.EndInvoke(result));
22                }
,
23                func);
24
25            //后台线程方法
26            BackgroundWorker worker = new BackgroundWorker();
27            worker.DoWork += (s,e) => e.Result = Square((int)e.Argument);
28            worker.RunWorkerCompleted += (s,e) => Console.WriteLine(e.Result);
29            worker.RunWorkerAsync(40);
30
31            //多线程方法
32            Thread thread = new Thread(new ThreadStart(() => Console.WriteLine(Square(50))));
33            thread.Start();
34
35            Console.ReadLine();           
36        }

37
38        //可以为耗时的操作
39        private static int Square(int x)
40        {
41            return x * x;
42        }

43    }

https://files.cnblogs.com/guozili/CodeTimer.rar

 

posted on 2009-02-27 17:45  guozili  阅读(803)  评论(3编辑  收藏  举报