public class MyEventArgs { private int _rate; public int Rate { get { return _rate; } } public MyEventArgs(int rate) { this._rate=rate; } } //1。自定义事件参数 public class MyObject {
//2.声明代理
//3.声明事件 public delegate void MyEventHandler(object sender,MyEventArgs e); public event MyEventHandler MyEvent; public void ALongTimeMethod(int time) { Console.WriteLine("主线程方法开始"); for(int i=0;i<100;i++) { System.Threading.Thread.Sleep(time); OnMyEvent(new MyEventArgs(i)); //激发事件 } Console.WriteLine("主线程方法结束"); } //4. 激发事件函数 protected void OnMyEvent(MyEventArgs e) { if (MyEvent!=null) { MyEvent(this,e); } } }
事件处理
class MyClient { [STAThread] static void Main(string[] args) { DateTime dt=DateTime.Now; MyObject obj=new MyObject(); obj.MyEvent+=new MyObject.MyEventHandler(obj_MyEvent); //为事件绑定方法 obj.ALongTimeMethod(50); Console.WriteLine("用了"+((TimeSpan)(DateTime.Now-dt)).TotalSeconds+"秒"); Console.ReadLine(); } public static void obj_MyEvent(object sender,MyEventArgs e) { Console.WriteLine("主线程方法完成了"+e.Rate+"%"); } }