1. 程式人生 > >事件模型

事件模型

線程安全 sender get not rlock chan 擴展類 pri new

  1 //事件通知類
  2 using System;
  3 using System.Collections.Generic;
  4 using System.Linq;
  5 using System.Text;
  6 using System.Threading.Tasks;
  7 
  8 namespace EventDemo
  9 {
 10     public class NotifyEventArgs : EventArgs
 11     {
 12         private readonly string notifyName;
13 public NotifyEventArgs(string name) 14 { 15 notifyName = name; 16 } 17 18 public string NotifyName 19 { 20 get { return notifyName; } 21 } 22 } 23 24 25 public class EventNotify 26 {
27 public event EventHandler<NotifyEventArgs> NewNotify; 28 29 public void Notify(string name) 30 { 31 NotifyEventArgs arg = new NotifyEventArgs(name); 32 arg.Raise(this, ref NewNotify); 33 } 34 } 35 } 36 37 38
//事件接受類 39 using System; 40 using System.Collections.Generic; 41 using System.Linq; 42 using System.Text; 43 using System.Threading.Tasks; 44 45 namespace EventDemo 46 { 47 public class EventReceive 48 { 49 string name; 50 public EventReceive(string name,EventNotify en) 51 { 52 this.name = name; 53 en.NewNotify += Receive; 54 } 55 56 private void Receive(object sender, NotifyEventArgs args) 57 { 58 Console.WriteLine(name+ " receive:"+args.NotifyName); 59 } 60 } 61 } 62 63 64 //線程安全事件擴展類 65 using System; 66 using System.Collections.Generic; 67 using System.Linq; 68 using System.Text; 69 using System.Threading; 70 using System.Threading.Tasks; 71 72 namespace EventDemo 73 { 74 public static class EventArgsExtensions 75 { 76 public static void Raise<T>(this T e, object sender, ref EventHandler<T> eventDelegate) where T : EventArgs 77 { 78 EventHandler<T> temp = Interlocked.CompareExchange(ref eventDelegate,null,null); 79 if (temp != null) 80 { 81 temp(sender,e); 82 } 83 } 84 } 85 } 86 87 88 //調用類 89 using System; 90 using System.Collections.Generic; 91 using System.Linq; 92 using System.Text; 93 using System.Threading.Tasks; 94 95 namespace EventDemo 96 { 97 class Program 98 { 99 static void Main(string[] args) 100 { 101 EventNotify notify = new EventNotify(); 102 103 EventReceive receive = new EventReceive("reveive1", notify); 104 EventReceive receive2 = new EventReceive("reveive2", notify); 105 EventReceive receive3 = new EventReceive("reveive3", notify); 106 107 notify.Notify("notify1"); 108 109 Console.ReadLine(); 110 } 111 } 112 }

事件模型