问题
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