事件模型

 //事件通知类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Threading.Tasks; namespace EventDemo { public class NotifyEventArgs : EventArgs { private readonly string notifyName; public NotifyEventArgs(string name) { notifyName = name; } public string NotifyName { get { return notifyName; } } } public class EventNotify { public event EventHandler<NotifyEventArgs> NewNotify; public void Notify(string name) { NotifyEventArgs arg = new NotifyEventArgs(name); arg.Raise(this, ref NewNotify); } } } //事件接受类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventDemo { public class EventReceive { string name; public EventReceive(string name,EventNotify en) { this.name = name; en.NewNotify += Receive; } private void Receive(object sender, NotifyEventArgs args) { Console.WriteLine(name+ " receive:"+args.NotifyName); } } } //线程安全事件扩展类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EventDemo { public static class EventArgsExtensions { public static void Raise<T>(this T e, object sender, ref EventHandler<T> eventDelegate) where T : EventArgs { EventHandler<T> temp = Interlocked.CompareExchange(ref eventDelegate,null,null); if (temp != null) { temp(sender,e); } } } } //调用类 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EventDemo { class Program { static void Main(string[] args) { EventNotify notify = new EventNotify(); EventReceive receive = new EventReceive("reveive1", notify); EventReceive receive2 = new EventReceive("reveive2", notify); EventReceive receive3 = new EventReceive("reveive3", notify); notify.Notify("notify1"); Console.ReadLine(); } } }

 

posted on 2017-08-23 23:33  强博员  阅读(138)  评论(0)    收藏  举报

导航