Do Multiple Asyncronous Invocations REQUIRE unique userStates?
I'm working on a C# application in which I set up a few asynchronous function calls using delegates. These calls will be subject to multiple-invocations, so I have to use the overload of the delegate's BeginInvoke
method which takes a userState
argument; e.g.:
callerDelegate.BeginInvoke([fn_args...], callback, userState)
On the Event-based Asynchronous Pattern Overview page on MSDN, it says about userState:
There are potentially two overloads for the asynchronous operations: single-invocation and multiple-invocation. You can distinguish these two forms by their method signatures: the multiple-invocation form has an extra parameter called userState. This form makes it possible for your code to call Method1Async(string param, object userState) multiple times without waiting for any pending asynchronous operations to finish. If, on the other hand, you try to call Method1Async(string param) before a previous invocation has completed, the method raises an InvalidOperationException.
The userState parameter for the multiple-invocation overloads allows you to distinguish among asynchronous operations. You provide a unique value (for example, a GUID or hash code) for each call to Method1Async(string param, object userState), and when each operation is com开发者_运维技巧pleted, your event handler can determine which instance of the operation raised the completion event.
My question is: does the userState
have to be unique? The wording can be construed to make it merely a recommendation, or just pertinent to their example. I do need to pass state to the callback, I just don't need it to be unique. (My application does not need to keep track of each individual instance of the call.) So, is uniqueness a requirement? (Perhaps the asynchronous framework of .NET needs it?)
Also, the quoted page is for event-based asynchronous operations; does this apply to my case (asynchronous calls using delegates) as well?
I've searched google and SO for a couple of days and have yet to find an answer.
Thanks in advance
It does not apply to your case. Begin
/End
are the IAsyncResult
asynchronous pattern, not the Event-based Asynchronous Pattern (EAP).
It affects EAP because usually the implementation uses AsyncOperationManager.CreateOperation
, which requires a unique user state. Even in this case, it's (usually) valid for end-user code to pass a null
user state; the EAP component would replace that with a new object
when it calls CreateOperation
.
精彩评论