• .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]);
                }
    
            }
  • 相关阅读:
    使用kubeadm部署K8S v1.17.0集群
    06Shell并发控制
    05Shell循环语句
    04Shell流程控制
    03Shell条件测试
    02Shell变量
    01Shell入门02-echo和printf
    01Shell入门01-bash Shell特性
    局域网部署ntp时间服务器
    聊聊、Mybatis集成Spring XML方式
  • 原文地址:https://www.cnblogs.com/dragon-L/p/5371251.html
Copyright © 2020-2023  润新知