Why does IAsyncResult require I keep a reference to the Delegate that BeginInvoked it?
I would like to be able to write something like:
new GenericDelegate(DoSomething).BeginInvoke(DoSomethingComplete); void DoSomethingComplete(IAsyncResult ar) { ar.EndInvoke(); }
You don’t need to keep your own reference to a delegate when doing a normal1 delegate
BeginInvoke; you can cast theIAsyncResultto anAsyncResultand retrieve the delegate from theAsyncDelegateproperty. And before anybody says ‘that’s a dirty hack’, it’s documented as being valid at MSDN.So you could write:
Note that you do still have to know the type of the original delegate (or at least, I haven’t found a way around this limitation; then again I haven’t tried).
1 By ‘normal’ here I mean a
BeginInvokeon a delegate instance, using the compiler-generated method. This technique of casting toAsyncResultis not guaranteed to work when using pre-defined methods, i.e. when using a class which declares its ownBeginX/EndXmethods. This is because the class may be doing something more clever internally such as blocking on IO completion ports, and may therefore use a different type ofIAsyncResult. However, in the scenario as posited, it will work just fine.