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

        }

 

相关文章:

  • 2021-11-14
  • 2021-11-03
  • 2021-06-19
  • 2021-07-21
  • 2021-12-01
  • 2021-10-09
  • 2021-11-19
  • 2022-01-02
猜你喜欢
  • 2021-06-13
  • 2021-12-13
  • 2021-08-28
  • 2021-11-10
  • 2021-10-18
  • 2022-12-23
相关资源
相似解决方案