异步编程中使用帮助类来实现Thread.Start()的示例
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
作者:CNXY Github:https://www.github.com/cnxy 出处:http://cnxy.me 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出,谢谢! |