问题描述
为什么代理需要在方法触发之前调用EndInvoke?如果我需要调用EndInvoke(阻止线程),那么它不是一个非常的异步调用呢?
Why does the delegate need to call the EndInvoke before the method fires? If i need to call the EndInvoke (which blocks the thread) then its not really an asynchronous call is it?
这是我试图运行的代码。 >
Here is the code im trying to run.
class Program
{
private delegate void GenerateXmlDelegate();
static void Main(string[] args)
{
GenerateXmlDelegate worker = new GenerateXmlDelegate(GenerateMainXml);
IAsyncResult result = worker.BeginInvoke(null, null);
}
private static void GenerateMainXml()
{
Thread.Sleep(10000);
Console.WriteLine("GenerateMainXml Called by delegate");
}
}
推荐答案
您需要调用 EndInvoke
的原因是为了避免内存泄漏; .Net将存储有关函数结果(或异常)的信息,直到调用 EndInvoke
。
The reason you need to call EndInvoke
is to avoid memory leaks; .Net will store information about the function's result (or exception) until you call EndInvoke
.
可以调用 EndInvoke
在您提供给 BeginInvoke
的完成处理程序中,并保留异步性质。
You can call EndInvoke
in the completion handler that you give to BeginInvoke
and retain the asyncronous nature.
编辑:
例如:
class Program {
private delegate void GenerateXmlDelegate();
static void Main(string[] args) {
GenerateXmlDelegate worker = new GenerateXmlDelegate(GenerateMainXml);
IAsyncResult result = worker.BeginInvoke(delegate {
try {
worker.EndInvoke();
} catch(...) { ... }
}, null);
}
private static void GenerateMainXml() {
Thread.Sleep(10000);
Console.WriteLine("GenerateMainXml Called by delegate");
}
}
如果要启动异步调用并忘记它,可以使用,像这样:
ThreadPool.QueueUserWorkItem(delegate { GenerateMainXml(); });
这篇关于为什么异步委托方法需要调用EndInvoke?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!