温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C#中怎么利用委托实现异步调用

发布时间:2021-07-19 15:31:55 来源:亿速云 阅读:116 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关C#中怎么利用委托实现异步调用,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

委托实现C#异步调用的步骤:

1.定义委托。

2.将要进行异步调用的方法“实例化”到定义的委托。

3.在委托上调用BeginInvoke方法。其中,BeginInvoke的参数由三个部分构成。***部分:所定义的委托的函数签名。

第二部分:希望调用的回调函数的委托。第三部分:自定义委托的实例(该实例将会在回调函数中的IAsyncResult的AsyncRState属性中重构出我们在步骤2中定义的委托实例,并借助这个实例来调用EndInvoke方法。)

4.如果我们希望在当前线程来处理异步调用的结果,则可以使用BeginInvoke方法返回一个IAsyncResult实例(例如ar)

并在当前线程等待。如果我们希望在异步线程中通过回调函数来处理结果,则我们需要在3中传递一个回调委托,并在该处理中调用EndInvoke方法。

委托实现C#异步调用的一段实例:

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)  {  //获得调用委托实例的引用  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();  }  }  }

关于C#中怎么利用委托实现异步调用就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI