歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C#使用delegate異步執行方法

C#使用delegate異步執行方法

日期:2017/3/1 10:35:39   编辑:Linux編程

在另外一個線程執行一個函數有很多種方法,這裡討論的是使用delegate的BeginInvoke方法,它的好處是在另一個線程中調用了函數,而且不用花費太多的開銷。

下面是使用delegate異步執行方法的示例:

[csharp]
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. object syncObject = new object();
  6. Test test = new Test();
  7. int index = 0;
  8. AutoResetEvent signal = new AutoResetEvent(false);
  9. for (int i = 0; i < 10; i++)
  10. {
  11. test.BeginDoAction(delegate(object sender, EventArgs e)
  12. {
  13. lock (syncObject)
  14. {
  15. Interlocked.Increment(ref index);
  16. if (index == 10)
  17. signal.Set();
  18. Console.WriteLine("Receive result.");
  19. }
  20. });
  21. }
  22. Console.WriteLine("Waiting signal.");
  23. signal.WaitOne();
  24. Console.WriteLine("Signaled.");
  25. Console.ReadLine();
  26. }
  27. }
  28. public delegate int GetDelegate();
  29. class Test
  30. {
  31. private EventHandler<EventArgs> callbackCompleted;
  32. public void BeginDoAction(EventHandler<EventArgs> pCallbackCompleted)
  33. {
  34. Console.WriteLine("Begin do action.");
  35. callbackCompleted = pCallbackCompleted;
  36. AsyncCallback callback = OnCompleted;
  37. GetDelegate getDelegate = DoAction;
  38. getDelegate.BeginInvoke(callback, null);
  39. }
  40. public int DoAction()
  41. {
  42. Console.WriteLine("Do action");
  43. Thread.Sleep(20000);
  44. return 1;
  45. }
  46. private void OnCompleted(IAsyncResult result)
  47. {
  48. GetDelegate getDelegate = ((AsyncResult)result).AsyncDelegate as GetDelegate;
  49. int print = getDelegate.EndInvoke(result);
  50. if (callbackCompleted != null)
  51. callbackCompleted(this, EventArgs.Empty);
  52. }
  53. }
最終顯示結果如下,說明函數被異步調用。


delegate是在另一個線程上異步執行一個方法的一種方式,但是它的使用也有一定的局限,由於delegate實際上是使用thread pool進行異步執行的,因此thread pool本身就成了這種調用方式的制約,比方說thread pool的尺寸或者其所能執行的線程數等等。因此並不是所有的異步方法調用都適合用delegate方式調用。

Copyright © Linux教程網 All Rights Reserved