• 委托与事件(五)


    通过事件可以订阅发布者的消息,存在异步问题,即如何让订阅者不影响发布者的执行,只是单纯的获取发布者的数据信息。

    以下代码完全取自张子阳博客

    • 发布者
     1 public class Publisher
     2 {
     3     //定义事件
     4     public event EventHandler MyEvent;
     5     public void DoSomething()
     6     {
     7         Console.WriteLine("DoSomething incoked!");
     8 
     9         if (MyEvent != null)
    10         {
    11             //获取多播委托的调用列表
    12             Delegate[] delArray = MyEvent.GetInvocationList();
    13             //异步执行委托
    14             foreach(Delegate del in delArray)
    15             {
    16                 EventHandler method = (EventHandler)del;
    17                 method.BeginInvoke(null, EventArgs.Empty, null, null);
    18             }
    19         }
    20     }
    21 }
    • 订阅者
     1     //第一个订阅者
     2     public class Subscriber1
     3     {
     4         public void OnEvent(object sender, EventArgs e)
     5         {
     6             Thread.Sleep(TimeSpan.FromSeconds(3));
     7             Console.WriteLine("Waited for 5 seconds, subscriber1 invoked!");
     8         }
     9     }
    10     //第二个订阅者
    11     public class Subscriber2
    12     {
    13         public void OnEvent(object sender, EventArgs e)
    14         {
    15             //throw new Exception("Subscriber2 Failed");
    16             Console.WriteLine("Waited for 0 seconds, subscriber2 invoked!");
    17         }
    18     }
    19     //第三个订阅者
    20     public class Subscriber3
    21     {
    22         public void OnEvent(object sender, EventArgs e)
    23         {
    24             Thread.Sleep(TimeSpan.FromSeconds(2));
    25             Console.WriteLine("Waited for 3 seconds, subscriber3 invoked!");
    26         }
    27     }
    • Main函数:
     1 static void Main(string[] args)
     2 {
     3     Publisher pub = new Publisher();
     4     pub.MyEvent += (new Subscriber1()).OnEvent;
     5     pub.MyEvent += (new Subscriber2()).OnEvent;
     6     pub.MyEvent += (new Subscriber3()).OnEvent;
     7 
     8     pub.DoSomething();
     9 
    10     Console.WriteLine("control back to client!
    ");
    11     Console.ReadLine();
    12 }

    输出结果:

  • 相关阅读:
    转载:【Oracle 集群】RAC知识图文详细教程(三)--RAC工作原理和相关组件
    转载:【Oracle 集群】RAC知识图文详细教程(一)--集群概念介绍
    转载:【Oracle 集群】RAC知识图文详细教程(二)--Oracle 集群概念及原理
    题目总结
    面试题(包含答案)
    ElementUI动态表格数据转换formatter
    父组件搜索列表 给 子组件传值问题
    项目提取公共接口方法
    数组常用方法总结
    vue全局注册
  • 原文地址:https://www.cnblogs.com/imstrive/p/6075251.html
Copyright © 2020-2023  润新知