异步编程练习
1
class Program
2
{
3
static void Main(string[] args)
4
{
5
//异步委托方法一
6
Func<int, int> func = new Func<int, int>(Square);
7
IAsyncResult ar1= func.BeginInvoke(10, null, null);
8
while (!ar1.IsCompleted)
9
Console.WriteLine(func.EndInvoke(ar1));
10
11
//异步委托方法二
12
IAsyncResult ar2 = func.BeginInvoke(20, null, null);
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

浙公网安备 33010602011771号