When writing implementations of the asynchronous use method using the BeginInvoke / EndInvoke template, the code may look something like this (and so you guess that it is an asynchronous shell around the cache):
IAsyncResult BeginPut(string key, object value) { Action<string, object> put = this.cache.Put; return put.BeginInvoke(key, value, null, null); } void EndPut(IAsyncResult asyncResult) { var put = (Action<string, object>)((AsyncResult)asyncResult).AsyncDelegate; put.EndInvoke(asyncResult); }
This works fine because he knows what a delegate type is, so it can be distinguished. However, it starts to get confused when you have two Put methods, because although the method returns void, you seem to need to give it to a strongly typed delegate to end the call, for example.
IAsyncResult BeginPut(string key, object value) { Action<string, object> put = this.cache.Put; return put.BeginInvoke(key, value, null, null); } IAsyncResult BeginPut(string region, string key, object value) { Action<string, string, object> put = this.cache.Put; return put.BeginInvoke(region, key, value, null, null); } void EndPut(IAsyncResult asyncResult) { var put = ((AsyncResult)asyncResult).AsyncDelegate; var put1 = put as Action<string, object>; if (put1 != null) { put1.EndInvoke(asyncResult); return; } var put2 = put as Action<string, string, object>; if (put2 != null) { put2.EndInvoke(asyncResult); return; } throw new ArgumentException("Invalid async result", "asyncResult"); }
I hope there is a cleaner way to do this, because the delegate's only concern is the type of return (in this case void), and not the arguments that were provided to him. But I racked my brains and asked others in the office, and no one can come up with an answer.
I know that one solution is to write a custom IAsyncResult , but such a difficult task with potential IAsyncResult problems around things like the lazy WaitHandle creation, that I would rather have this slightly hacked code than go down this route.
Any ideas on how to end a call without a cascading set of is checks?