事件与委托(之监听线程的实现)
以下示例通过事件{s的值是a}的监听,实现当事件{s的值是a}发生时,触发事件的处理函数。
其中swith作为控制事件防止无限触发的开关。
该模型可用作监听线程。
using System; using System.Threading.Tasks; /*定义委托类型MyEventHandler(object sender, MyEventArgs e) * 定义事件参数类 * 定义事件处理方法,它与delegate对象具有相同的参数和返回值类型 * 用event关键字委托类型MyEventHandler定义事件对象 * 构造函数中绑定:事件对象+=事件处理函数的委托 * 以调用delegate的方式写事件触发函数 * 外部通过调用RaiseEvent触发事件 */ public class EventTest { // 步骤1,定义delegate对象 public delegate void MyEventHandler(object sender, MyEventArgs e); public static string s;//被监视的值,其实应该增加s改变事件,当s改变,去改变sbuf,本示例中手动去给sbuf赋值为s public static bool swith;//循环执行的开关 // 步骤4,用event关键字定义事件对象 private event MyEventHandler myevent; private MyEventCls myecls=new MyEventCls(); public static Task t1; public static void swithOnOff() { if (swith) swith = false; else swith = true; } //构造函数中绑定:事件对象+=事件处理函数的委托 public EventTest() { // 步骤5,用+=操作符将事件添加到队列中 this.myevent += new MyEventHandler(myecls.MyEventFunc); //监听线程的创建 //新建一个Task t1 = new Task(() => { while (true) { if (swith && s == "a") RaiseEvent(s); } }); //启动Task t1.Start(); } // 步骤6,以调用delegate的方式写事件触发函数 protected void OnMyEvent(MyEventArgs e) { if (myevent != null) myevent(this, e); //可写作 //myevent?.Invoke(this, e); } // 触发事件的函数,本示例中为监听线程的写法:监视s的值,当其为a时触发事件 public void RaiseEvent(string o) { MyEventArgs e = new MyEventArgs(); e.s = s; // 步骤7,触发事件 OnMyEvent(e); //关闭开关 swith = false; } } // 步骤2(定义事件参数类) public class MyEventArgs { public string s; } public class MyEventCls { // 步骤3,定义事件处理方法,它与delegate对象具有相同的参数和返回值类型 public void MyEventFunc(object sender, MyEventArgs e) { Console.WriteLine("监听s是不是“a”的线程执行!"); } } class Program { static void Main(string[] args) { EventTest et = new EventTest(); Console.ForegroundColor = ConsoleColor.Cyan; while (true) { Console.Write("Please input ''a'':"); string s = Console.ReadLine(); Console.WriteLine("本次输入:"+s); EventTest.s = s; EventTest.swith = true; } }

浙公网安备 33010602011771号