我可以使用委托的单个实例来启动多个异步请求吗?
只是想知道当您想要进行多个异步调用时,是否有人可以澄清在某个委托的实例上使用 BeginInvoke
,因为 MSDN 文档根本没有真正涵盖/提及这一点。
我想要做的事情如下:
MyDelegate d = new MyDelegate(this.TargetMethod);
List<IAsyncResult> results = new List<IAsyncResult>();
//Start multiple asynchronous calls
for (int i = 0; i < 4; i++)
{
results.Add(d.BeginInvoke(someParams, null, null));
}
//Wait for all my calls to finish
WaitHandle.WaitAll(results.Select(r => r.AsyncWaitHandle).ToArray());
//Process the Results
问题是我可以使用委托的一个实例来执行此操作,还是需要为每个单独的调用提供一个委托实例?
鉴于 EndInvoke()
采用 IAsyncResult
作为参数,我认为前者是正确的,但我在文档中看不到任何指示任何一种方式的内容。
Just wondered if someone could clarify the use of BeginInvoke
on an instance of some delegate when you want to make multiple asynchronous calls since the MSDN documentation doesn't really cover/mention this at all.
What I want to do is something like the following:
MyDelegate d = new MyDelegate(this.TargetMethod);
List<IAsyncResult> results = new List<IAsyncResult>();
//Start multiple asynchronous calls
for (int i = 0; i < 4; i++)
{
results.Add(d.BeginInvoke(someParams, null, null));
}
//Wait for all my calls to finish
WaitHandle.WaitAll(results.Select(r => r.AsyncWaitHandle).ToArray());
//Process the Results
The question is can I do this with one instance of the delegate or do I need an instance of the delegate for each individual call?
Given that EndInvoke()
takes an IAsyncResult
as a parameter I would assume that the former is correct but I can't see anything in the documentation to indicate either way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,没问题。每次调用 BeginInvoke() 都会得到不同的 IAsyncResult。委托对象本身没有与启动线程关联的状态。
Yes, no problem. You'll get a different IAsyncResult for each call to BeginInvoke(). There's no state associated with the started thread in the delegate object itself.