转自原文多线程简单示例
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Runtime.Remoting.Messaging; namespace ThreadMulti { class Program { delegate string MyDelegate(string msg); static object locker=new object(); static void Main(string[] args) { System.Console.WriteLine("---------------------"); WriteLine("Main Thread example.", ConsoleColor.Green); WriteLine("Async Thread example.", ConsoleColor.Red); WriteLine("Async Thread CallBack", ConsoleColor.Cyan); System.Console.WriteLine("--------------------- "); WriteLine("Main Thread Begin ,ThreadId is : " + Thread.CurrentThread.ManagedThreadId, ConsoleColor.Green); MyDelegate myDelegate = new MyDelegate(Messgae); //异步调用,传入参数为object类型,此处用stirng示例 myDelegate.BeginInvoke("Hello Thread World!", Completed, "传参示例"); //模拟线程工作,可以看到两线程同时工作 for (int i = 0; i < 5; i++) { Thread.Sleep(1000); WriteLine("Main Thread Works!", ConsoleColor.Green); } WriteLine("Main Thread Complete!", ConsoleColor.Green); Console.ReadKey(); } static string Messgae(string msg) { WriteLine("Async Thread Begin ,ThreadId is : " + Thread.CurrentThread.ManagedThreadId, ConsoleColor.Red); //模拟线程工作,可以看到两线程同时工作 for (int i = 0; i < 5; i++) { Thread.Sleep(500); WriteLine("Async Thread Works!", ConsoleColor.Red); } WriteLine("Async Thread Complete!", ConsoleColor.Red); return msg; } static void Completed(IAsyncResult iresult) { //通过 Thread.CurrentThread.ManagedThreadId 可以看出,回调函数运行在异步线程上 WriteLine("Async Thread CallBack Begin,ThreadId is : " + Thread.CurrentThread.ManagedThreadId, ConsoleColor.Cyan); AsyncResult result = iresult as AsyncResult; //使用AsyncDelegate获得委托 MyDelegate myDelegate = result.AsyncDelegate as MyDelegate; //使用EndInvoke获取返回值 string data = myDelegate.EndInvoke(result); //用 AsyncState 获得传入的参数(即19行“传参示例”四个字) string asyncState = result.AsyncState.ToString(); WriteLine("返回的数据:"+data, ConsoleColor.Cyan); WriteLine("异步调用结果状态:" + asyncState, ConsoleColor.Cyan); //模拟回调函数工作 for (int i = 0; i < 3; i++) { Thread.Sleep(500); WriteLine("Async Thread CallBack Works!", ConsoleColor.Cyan); } WriteLine("Async Thread CallBack Complete!", ConsoleColor.Cyan); } static void WriteLine(string data, ConsoleColor color) { lock (locker) { Console.ForegroundColor = color; Console.WriteLine(data); Console.ResetColor(); } } } }
结果: