【问题标题】:How to call any method asynchronously in c#如何在c#中异步调用任何方法
【发布时间】:2011-04-06 08:12:24
【问题描述】:

谁能给我看一段小sn-p代码,演示如何在c#中异步调用方法?

【问题讨论】:

    标签: c# asynchronous


    【解决方案1】:

    如果你使用 action.BeginInvoke(),你 have to call EndInvoke 在某个地方 - 否则框架必须在堆上保存异步调用的结果,从而导致内存泄漏。

    如果您不想使用 async/await 关键字跳转到 C# 5,您可以只使用 .Net 4 中的 Task Parallels 库。它比使用 BeginInvoke/EndInvoke 好得多,并且提供了一种简洁的方法对异步作业进行一劳永逸:

    using System.Threading.Tasks;
    ...
    void Foo(){}
    ...
    new Task(Foo).Start();
    

    如果您有方法可以调用接受参数的方法,则可以使用 lambda 来简化调用,而无需创建委托:

    void Foo2(int x, string y)
    {
        return;
    }
    ...
    new Task(() => { Foo2(42, "life, the universe, and everything");}).Start();
    

    我很确定(但不可否认)C# 5 async/await 语法只是任务库周围的语法糖。

    【讨论】:

    • 如果还不清楚,最后的假设 re: async/await 是正确的,但它会极大地改变你的代码的外观。
    • 我正在尝试使用一种创建事件然后委托的方法,这是正确的吗?如果是这样,我该如何结束任务。干杯
    【解决方案2】:

    从 .Net 4.5 开始,您可以使用 Task.Run 来简单地启动一个操作:

    void Foo(string args){}
    ...
    Task.Run(() => Foo("bar"));
    

    Task.Run vs Task.Factory.StartNew

    【讨论】:

      【解决方案3】:

      这是一种方法:

      // The method to call
      void Foo()
      {
      }
      
      
      Action action = Foo;
      action.BeginInvoke(ar => action.EndInvoke(ar), null);
      

      当然,如果方法具有不同的签名,您需要将Action 替换为另一种类型的委托

      【讨论】:

      • 当我们调用 foo 那么我如何传递你没有显示的参数?
      • 可以放置一个对象来代替 null。让 Foo 接受一个对象类型的输入参数。然后,您必须将对象转换为 Foo 中的适当类型。
      【解决方案4】:

      如果您有能力玩新东西,请查看 MSDN 文章 Asynchronous Programming with Async and Await。它已添加到 .NET 4.5。

      来自链接的示例代码 sn-p(它本身来自 this MSDN sample code project):

      // Three things to note in the signature: 
      //  - The method has an async modifier.  
      //  - The return type is Task or Task<T>. (See "Return Types" section.)
      //    Here, it is Task<int> because the return statement returns an integer. 
      //  - The method name ends in "Async."
      async Task<int> AccessTheWebAsync()
      { 
          // You need to add a reference to System.Net.Http to declare client.
          HttpClient client = new HttpClient();
      
          // GetStringAsync returns a Task<string>. That means that when you await the 
          // task you'll get a string (urlContents).
          Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com");
      
          // You can do work here that doesn't rely on the string from GetStringAsync.
          DoIndependentWork();
      
          // The await operator suspends AccessTheWebAsync. 
          //  - AccessTheWebAsync can't continue until getStringTask is complete. 
          //  - Meanwhile, control returns to the caller of AccessTheWebAsync. 
          //  - Control resumes here when getStringTask is complete.  
          //  - The await operator then retrieves the string result from getStringTask. 
          string urlContents = await getStringTask;
      
          // The return statement specifies an integer result. 
          // Any methods that are awaiting AccessTheWebAsync retrieve the length value. 
          return urlContents.Length;
      }
      

      引用:

      如果AccessTheWebAsync 在调用 GetStringAsync 和等待其完成之间没有任何工作可以做,您可以通过在以下单个语句中调用和等待来简化代码。

      string urlContents = await client.GetStringAsync();
      

      更多详情请见link

      【讨论】:

      • 我将如何使用这种技术并设置超时?
      【解决方案5】:
      public partial class MainForm : Form
      {
          Image img;
          private void button1_Click(object sender, EventArgs e)
          {
              LoadImageAsynchronously("http://media1.santabanta.com/full5/Indian%20%20Celebrities(F)/Jacqueline%20Fernandez/jacqueline-fernandez-18a.jpg");
          }
      
          private void LoadImageAsynchronously(string url)
          {
              /*
              This is a classic example of how make a synchronous code snippet work asynchronously.
              A class implements a method synchronously like the WebClient's DownloadData(…) function for example
                  (1) First wrap the method call in an Anonymous delegate.
                  (2) Use BeginInvoke(…) and send the wrapped anonymous delegate object as the last parameter along with a callback function name as the first parameter.
                  (3) In the callback method retrieve the ar's AsyncState as a Type (typecast) of the anonymous delegate. Along with this object comes EndInvoke(…) as free Gift
                  (4) Use EndInvoke(…) to retrieve the synchronous call’s return value in our case it will be the WebClient's DownloadData(…)’s return value.
              */
              try
              {
                  Func<Image> load_image_Async = delegate()
                  {
                      WebClient wc = new WebClient();
                      Bitmap bmpLocal = new Bitmap(new MemoryStream(wc.DownloadData(url)));
                      wc.Dispose();
                      return bmpLocal;
                  };
      
                  Action<IAsyncResult> load_Image_call_back = delegate(IAsyncResult ar)
                  {
                      Func<Image> ss = (Func<Image>)ar.AsyncState;
                      Bitmap myBmp = (Bitmap)ss.EndInvoke(ar);
      
                      if (img != null) img.Dispose();
                      if (myBmp != null)
                          img = myBmp;
                      Invalidate();
                      //timer.Enabled = true;
                  };
                  //load_image_Async.BeginInvoke(callback_load_Image, load_image_Async);             
                  load_image_Async.BeginInvoke(new AsyncCallback(load_Image_call_back), load_image_Async);             
              }
              catch (Exception ex)
              {
      
              }
          }
          protected override void OnPaint(PaintEventArgs e)
          {
              if (img != null)
              {
                  Graphics grfx = e.Graphics;
                  grfx.DrawImage(img,new Point(0,0));
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 2017-03-06
        • 1970-01-01
        相关资源
        最近更新 更多