本文介绍了如果人们总是调用EndInvoke内的AsyncCallback一个代表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读使用的AsyncCallback ,有这个code片段:

I read the Use AsyncCallback, there is this code snippet:

using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
class MainClass
{
  delegate int MyDelegate(string s);

  static void Main(string[] args)
  {
    MyDelegate X = new MyDelegate(DoSomething);
    AsyncCallback cb = new AsyncCallback(DoSomething2);
    IAsyncResult ar = X.BeginInvoke("Hello", cb, null);

    Console.WriteLine("Press any key to continue");
    Console.ReadLine();
  }
  static int DoSomething(string s)
  {
    Console.WriteLine("doooooooooooooooo");
    return 0;
  }

  static void DoSomething2(IAsyncResult ar)
  {
    MyDelegate X = (MyDelegate)((AsyncResult)ar).AsyncDelegate;
    X.EndInvoke(ar);
  }
}

请注意,在了doSomething2 ,这是一个的AsyncCallback ,委托明确的命令,杀死 EndInvoke会

Note that in DoSomething2, which is an AsyncCallback, the delegate is explicitly killed by the command EndInvoke.

这真的有必要?因为的AsyncCallback 将不会被调用,除非委托方法运行完毕。

Is this really necessary? Because AsyncCallback won't get called unless and until the delegate method is finished running.

推荐答案

调用的EndInvoke()是非常重要的。如果背景方法生成异常然后调用EndInvoke会()将提高该异常,让你的主线程来处理它。此外,如果背景方法具有一个返回值时,则主线程需要调用EndInvoke()来检索该值。

Calling EndInvoke() is very important. If the background method generates an exception then calling EndInvoke() will raise that Exception, allowing your main thread to handle it. Also, if the background method has a return value then the main thread needs to call EndInvoke() to retrieve that value.

如果你的后台线程在任何一种情况属于(生成异常或有返回值),您的的调用EndInvoke(),则后台线程不会freed--本质上导致资源泄漏。

If your background thread falls under either of these situations (generates an exception or has a return value) and you don't call EndInvoke() then the background thread won't be freed--essentially resulting in a resource leak.

这篇关于如果人们总是调用EndInvoke内的AsyncCallback一个代表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:42