问题描述
为什么需要委托方法火灾前致电EndInvoke会?如果我需要调用EndInvoke会(以阻止该线程),那么它不是一个真正的异步调用呢?
下面是code IM试图运行。
类节目
{
私人委托无效GenerateXmlDelegate(); 静态无效的主要(字串[] args)
{
GenerateXmlDelegate工人=新GenerateXmlDelegate(GenerateMainXml);
IAsyncResult的结果= worker.BeginInvoke(NULL,NULL);
} 私有静态无效GenerateMainXml()
{
Thread.sleep代码(10000);
Console.WriteLine(被代表呼吁GenerateMainXml);
}
}
您需要调用的原因 EndInvoke会
是为了避免内存泄漏; .NET将存储有关函数的结果(或异常)的信息,直到您调用 EndInvoke会
。
您可以致电 EndInvoke会
在您为的BeginInvoke完成处理程序
并保留asyncronous性质。
修改
例如:
类节目{
私人委托无效GenerateXmlDelegate(); 静态无效的主要(字串[] args){
GenerateXmlDelegate工人=新GenerateXmlDelegate(GenerateMainXml);
IAsyncResult的结果= worker.BeginInvoke(代表{
尝试{
worker.EndInvoke();
}赶上(...){...}
}, 空值);
} 私有静态无效GenerateMainXml(){
Thread.sleep代码(10000);
Console.WriteLine(被代表呼吁GenerateMainXml);
}
}
如果你想火一个异步调用,并忘掉它,你可以使用,像这样的:
ThreadPool.QueueUserWorkItem(代表{GenerateMainXml();});
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");
}
}
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
.
You can call EndInvoke
in the completion handler that you give to BeginInvoke
and retain the asyncronous nature.
EDIT:
For example:
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");
}
}
If you want to fire an async call and forget about it, you can use the ThreadPool, like this:
ThreadPool.QueueUserWorkItem(delegate { GenerateMainXml(); });
这篇关于为什么异步委托方法调用需要EndInvoke会?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!