zoukankan      html  css  js  c++  java
  • 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. 执行结果:

  • 相关阅读:
    bzoj1878: [SDOI2009]HH的项链
    bzoj1053: [HAOI2007]反素数ant
    bzoj2456: mode
    bzoj2330: [SCOI2011]糖果
    bzoj1050: [HAOI2006]旅行comf
    bzoj1047: [HAOI2007]理想的正方形
    bzoj1968: [Ahoi2005]COMMON 约数研究
    bzoj1046: [HAOI2007]上升序列
    bzoj2440: [中山市选2011]完全平方数
    bzoj1202: [HNOI2005]狡猾的商人
  • 原文地址:https://www.cnblogs.com/ChengWenHao/p/CSharpOtherPart4.html
Copyright © 2011-2022 走看看