• C# -- 使用委托 delegate 执行异步操作


    C# -- 使用委托 delegate 执行异步操作

    委托是一种安全地封装方法的类型,它与 C 和 C++ 中的函数指针类似。 与 C 中的函数指针不同,委托是面向对象的、类型安全的和保险的。

    委托的类型由委托的名称定义。

    1. 使用委托异步执行方法

        class Program
        {
            public delegate void myWorking(string s);
    
            static void Main(string[] args)
            {
                Console.WriteLine("主线程开始....线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
                myWorking myWork1 = new myWorking(w1 => Working(w1));
                myWorking myWork2 = new myWorking(w2 => Working(w2));
                myWorking myWork3 = new myWorking(w3 => Working(w3));
                myWorking myWork4 = new myWorking(w4 => Working(w4));
                myWorking myWork5 = new myWorking(w5 => Working(w5));
                
                //回调函数
                AsyncCallback callback=new AsyncCallback(s=>Console.WriteLine("执行完成,线程ID:{0}",Thread.CurrentThread.ManagedThreadId));
    
                //BeginInvoke异步执行,会新启动其他线程去执行代码
                myWork1.BeginInvoke("唱歌", callback,null);
                myWork2.BeginInvoke("写代码", callback, null);
                myWork3.BeginInvoke("查资料", callback, null);
                myWork4.BeginInvoke("交作业", callback, null);
                myWork5.BeginInvoke("检查", callback, null);
    
                Console.WriteLine("主线程结束....线程ID:{0}", Thread.CurrentThread.ManagedThreadId);
                Console.ReadKey();
            }
    
            private static void Working(string strWork)
            {
                Console.WriteLine(strWork+".....线程ID:{0}",Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(3000);
            }
        }

    2. 执行结果:

  • 相关阅读:
    十天冲刺之三
    设计模式-模板方法模式
    设计模式-观察者模式
    设计模式-迭代子模式
    设计模式-责任链模式
    设计模式-门面模式
    1395. Count Number of Teams
    747. Largest Number At Least Twice of Others
    1160. Find Words That Can Be Formed by Characters
    1539. Kth Missing Positive Number
  • 原文地址:https://www.cnblogs.com/ChengWenHao/p/CSharpOtherPart4.html
Copyright © 2020-2023  润新知