1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading; 6 using System.Runtime.Remoting.Messaging; 7 8 namespace ThreadExample 9 { 10 class Program 11 { 12 delegate string MyDelegate(string msg); 13 static object locker=new object(); 14 15 static void Main(string[] args) 16 { 17 WriteLine("Main Thread Begin ,ThreadId is : " + Thread.CurrentThread.ManagedThreadId, ConsoleColor.Green); 18 MyDelegate myDelegate = new MyDelegate(Messgae); 19 //异步调用,传入参数为object类型,此处用stirng示例 20 myDelegate.BeginInvoke("Hello Thread World!", Completed, "传参示例"); 21 //模拟线程工作,可以看到两线程同时工作 22 for (int i = 0; i < 5; i++) 23 { 24 Thread.Sleep(1000); 25 WriteLine("Main Thread Works!", ConsoleColor.Green); 26 } 27 WriteLine("Main Thread Complete!", ConsoleColor.Green); 28 Console.ReadKey(); 29 } 30 31 static string Messgae(string msg) 32 { 33 WriteLine("Async Thread Begin ,ThreadId is : " + Thread.CurrentThread.ManagedThreadId, ConsoleColor.Red); 34 //模拟线程工作,可以看到两线程同时工作 35 for (int i = 0; i < 5; i++) 36 { 37 Thread.Sleep(500); 38 WriteLine("Async Thread Works!", ConsoleColor.Red); 39 } 40 WriteLine("Async Thread Complete!", ConsoleColor.Red); 41 return msg; 42 } 43 44 static void Completed(IAsyncResult iresult) 45 { 46 //通过 Thread.CurrentThread.ManagedThreadId 可以看出,回调函数运行在异步线程上 47 WriteLine("Async Thread CallBack Begin,ThreadId is : " + Thread.CurrentThread.ManagedThreadId, ConsoleColor.Cyan); 48 AsyncResult result = iresult as AsyncResult; 49 //使用AsyncDelegate获得委托 50 MyDelegate myDelegate = result.AsyncDelegate as MyDelegate; 51 //使用EndInvoke获取返回值 52 string data = myDelegate.EndInvoke(result); 53 //用 AsyncState 获得传入的参数(即19行“传参示例”四个字) 54 string asyncState = result.AsyncState.ToString(); 55 WriteLine(data, ConsoleColor.Cyan); 56 WriteLine(asyncState, ConsoleColor.Cyan); 57 //模拟回调函数工作 58 for (int i = 0; i < 3; i++) 59 { 60 Thread.Sleep(500); 61 WriteLine("Async Thread CallBack Works!", ConsoleColor.Cyan); 62 } 63 WriteLine("Async Thread CallBack Complete!", ConsoleColor.Cyan); 64 } 65 66 static void WriteLine(string data, ConsoleColor color) 67 { 68 lock (locker) 69 { 70 Console.ForegroundColor = color; 71 Console.WriteLine(data); 72 Console.ResetColor(); 73 } 74 } 75 } 76 }
结果:
原文:http://www.cnblogs.com/David-Huang/p/3747393.html