溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#中怎么利用委托實(shí)現(xiàn)異步調(diào)用

發(fā)布時間:2021-07-19 15:31:55 來源:億速云 閱讀:131 作者:Leah 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)C#中怎么利用委托實(shí)現(xiàn)異步調(diào)用,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

委托實(shí)現(xiàn)C#異步調(diào)用的步驟:

1.定義委托。

2.將要進(jìn)行異步調(diào)用的方法“實(shí)例化”到定義的委托。

3.在委托上調(diào)用BeginInvoke方法。其中,BeginInvoke的參數(shù)由三個部分構(gòu)成。***部分:所定義的委托的函數(shù)簽名。

第二部分:希望調(diào)用的回調(diào)函數(shù)的委托。第三部分:自定義委托的實(shí)例(該實(shí)例將會在回調(diào)函數(shù)中的IAsyncResult的AsyncRState屬性中重構(gòu)出我們在步驟2中定義的委托實(shí)例,并借助這個實(shí)例來調(diào)用EndInvoke方法。)

4.如果我們希望在當(dāng)前線程來處理異步調(diào)用的結(jié)果,則可以使用BeginInvoke方法返回一個IAsyncResult實(shí)例(例如ar)

并在當(dāng)前線程等待。如果我們希望在異步線程中通過回調(diào)函數(shù)來處理結(jié)果,則我們需要在3中傳遞一個回調(diào)委托,并在該處理中調(diào)用EndInvoke方法。

委托實(shí)現(xiàn)C#異步調(diào)用的一段實(shí)例:

using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using System.Threading;   namespace property  {  public class DelegateClass  {  public delegate int AsyncSampDelegate();  public event AsyncSampDelegate delEvent;   public void Run()  {  Console.WriteLine("The Run Thread is {0}",   Thread.CurrentThread.GetHashCode());  foreach (AsyncSampDelegate del in  delEvent.GetInvocationList())  {  del.BeginInvoke(new AsyncCallback(ReturnAsync), del);  }  }   public void ReturnAsync(IAsyncResult ar)  {  //獲得調(diào)用委托實(shí)例的引用  AsyncSampDelegate del = (AsyncSampDelegate)ar.AsyncState;  int result = del.EndInvoke(ar);  Console.WriteLine("The result is {0},  The Thread is {1}", result, Thread.CurrentThread.GetHashCode());  }  }   public class FirstSubscribe  {  private int myCount = 0;   public void AddFunToDel(DelegateClass tmpDel)  {  tmpDel.delEvent+=new DelegateClass.  AsyncSampDelegate(FirstFun);  }    public int FirstFun()  {  return myCount++;  }  }   public class SecondSubscribe  {  private int myCount = 0;   public void AddFunToDel(DelegateClass tmpDel)  {  tmpDel.delEvent+=new DelegateClass.  AsyncSampDelegate(SecondFun);  }   public int SecondFun()  {  return myCount += 2;  }  }   public class App  {  static void Main()  {  DelegateClass delClass = new DelegateClass();  FirstSubscribe fs = new FirstSubscribe();  SecondSubscribe ss = new SecondSubscribe();   fs.AddFunToDel(delClass);  ss.AddFunToDel(delClass);   Console.WriteLine("The Main Thread is {0}",   Thread.CurrentThread.GetHashCode());  delClass.Run();  Console.Read();  }  }  }

關(guān)于C#中怎么利用委托實(shí)現(xiàn)異步調(diào)用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI