异步编程中使用帮助类来实现Thread.Start()的示例

2017-12-25 15:29:20 浏览数 (2)

代码语言:javascript复制
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 
 7 namespace ConsoleApplication9
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13 
14 
15             // 异步调用 
16             // 将需传递给异步执行方法数据及委托传递给帮助器类 
17             ThreadWithState tws = new ThreadWithState(
18                "This report displays the number {0}.",
19                42,
20                new ExampleCallback(ResultCallback)
21             );
22             Thread t = new Thread(new ThreadStart(tws.ThreadProc));
23             t.Start();
24             Console.ReadKey();
25         }
26 
27         static void ResultCallback(int i)
28         {
29             Console.Write("No."   i   "n");
30         }
31     }
32 }
33 
34 // 包装异步方法的委托 
35 public delegate void ExampleCallback(int lineCount); 
36 // 帮助器类 
37   
38 public class ThreadWithState 
39 { 
40     private string boilerplate; 
41     private int value; 
42     private ExampleCallback callback; 
43    
44     public ThreadWithState(string text, int number, 
45         ExampleCallback callbackDelegate) 
46   
47     { 
48         boilerplate = text; 
49         value = number; 
50         callback = callbackDelegate; 
51     } 
52   
53     public void ThreadProc() 
54     { 
55         Console.WriteLine(boilerplate, value); 
56         // 异步执行完时调用回调 
57         if (callback != null) 
58             callback(1); 
59     } 
60 } 

运行结果:

摘自:http://www.cnblogs.com/heyuquan/archive/2012/12/16/2820775.html

0 人点赞