1. 程式人生 > >C# 委托事件的異步調用

C# 委托事件的異步調用

oid order AS ogr () 圖片 異步 技術分享 leg

技術分享圖片
 1         public class Publish
 2         {
 3             public delegate void PublishEventHandler(object sender,PublishEventArgs e);
 4             private event PublishEventHandler publish;
 5             private Delegate[] del;
 6             public class PublishEventArgs :EventArgs
 7             {
8 public string BookName { get; private set; } 9 public PublishEventArgs(string bookName) 10 { 11 this.BookName = bookName; 12 } 13 } 14 15 public void RegisterPublish(PublishEventHandler publish)
16 { 17 this.publish += publish; 18 } 19 public void UnRegisterPublish(PublishEventHandler publish) 20 { 21 this.publish -= publish; 22 } 23 24 public void OnPublish(PublishEventArgs e) 25 {
26 Console.WriteLine("OnDoPublish"); 27 if(publish != null) 28 publish(this,e); 29 } 30 31 public void OnPublishAsyn(PublishEventArgs e) 32 { 33 Console.WriteLine("OnDoPublish"); 34 if(publish != null) { 35 del = publish.GetInvocationList(); 36 foreach(Delegate item in del) { 37 PublishEventHandler Method = (PublishEventHandler)item; 38 Method.BeginInvoke(null,e,null,null); 39 } 40 } 41 } 42 }
View Code

技術分享圖片
 1       public class SubScriber
 2         {
 3             private string OrderName;
 4             public SubScriber(string orderName)
 5             {
 6                 this.OrderName = orderName;
 7             }
 8 
 9             public void publish(object sender,Test.Program.Publish.PublishEventArgs e)
10             {
11                 Console.WriteLine(OrderName + " Buy " + e.BookName
12                     + " " + Thread.CurrentThread.ManagedThreadId);
13                  Thread.Sleep(2000);
14             }
15         }
View Code

技術分享圖片
 1         static void Main(string[] args)
 2         {
 3             Publish pub = new Publish();
 4             SubScriber sub1 = new SubScriber("xiao zeng");
 5             SubScriber sub2 = new SubScriber("xiao Li");
 6             SubScriber sub3 = new SubScriber("xiao Wang");
 7             SubScriber sub4 = new SubScriber("xiao zhao");
 8             pub.RegisterPublish(sub1.publish);
 9             pub.RegisterPublish(sub2.publish);
10             pub.RegisterPublish(sub3.publish);
11             pub.RegisterPublish(sub4.publish);
12             pub.OnPublish(new Publish.PublishEventArgs("Tom And Jerry"));
13             pub.OnPublishAsyn(new Publish.PublishEventArgs("Tom And Jerry"));
14             Console.ReadLine();
15         }
View Code

C# 委托事件的異步調用