Is this a clean way to manage AsyncResults with Generic Methods?
Posted
by Michael Stum
on Stack Overflow
See other posts from Stack Overflow
or by Michael Stum
Published on 2010-04-19T02:57:30Z
Indexed on
2010/04/19
3:03 UTC
Read the original article
Hit count: 341
I've contributed Async Support to a Project I'm using, but I made a bug which I'm trying to fix. Basically I have this construct:
private readonly Dictionary<WaitHandle, object> genericCallbacks
= new Dictionary<WaitHandle, object>();
public IAsyncResult BeginExecute<T>(RestRequest request, AsyncCallback callback,
object state) where T : new()
{
var genericCallback = new RequestExecuteCaller<T>(this.Execute<T>);
var asyncResult = genericCallback.BeginInvoke(request, callback, state);
genericCallbacks[asyncResult.AsyncWaitHandle] = genericCallback;
return asyncResult;
}
public RestResponse<T> EndExecute<T>(IAsyncResult asyncResult) where T : new()
{
var cb = genericCallbacks[asyncResult.AsyncWaitHandle]
as RequestExecuteCaller<T>;
genericCallbacks.Remove(asyncResult.AsyncWaitHandle);
return cb.EndInvoke(asyncResult);
}
So I have a generic BeginExecute/EndExecute method pair. As I need to store the delegate that is called on EndExecute somewhere I created a dictionary.
I'm unsure about using WaitHandles as keys though, but that seems to be the only safe choice. Does this approach make sense? Are WaitHandles unique or could I have two equal ones?
Or should I instead use the State (and wrap any user provided state into my own State value)?
Just to add, the class itself is non-generic, only the Begin/EndExecute methods are generic.
© Stack Overflow or respective owner