Can I use a single instance of a delegate to start multiple Asynchronous Requests?

倖福魔咒の 提交于 2020-01-04 19:02:41

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/3044644/can-i-use-a-single-instance-of-a-delegate-to-start-multiple-asynchronous-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!