1. 不需要构造委托对象
ThreadPool.QueueUserWorkItem:通过线程池
public static void WorkItem() { ThreadPool.QueueUserWorkItem(SomeAsyncTask, 5); } public static void SomeAsyncTask(object o) { Console.WriteLine("SomeAsyncTask:{0}", 0); }
2. 不需要定义回调方法(lambda 表达式):
public static void CallbackWithouNewingADelegateObject() { ThreadPool.QueueUserWorkItem( obj => Console.WriteLine("SomeAsyncTask:{0}", obj), 5); }
3. 局部变量不需要手动包装到类中即可传给回调方法。
public static void UsingLocalVariablesInTheCallbackCode(int numToDo) { int[] squares = new int[numToDo]; AutoResetEvent done = new AutoResetEvent(false); for (int n = 0; n < squares.Length; n++) { ThreadPool.QueueUserWorkItem( obj => { int num = (int)obj; squares[num] = num * num; if (Interlocked.Decrement(ref numToDo) == 0) done.Set(); }, n ); } done.WaitOne(); for (int n = 0; n < squares.Length; n++) { Console.WriteLine("Index {0} ,square={1}", n, squares[n]); } }