.net 委托的简化语法

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]);
            }

        }

 

posted @ 2016-04-09 11:45  dragon.net  阅读(215)  评论(0编辑  收藏  举报