If I want to do a "fire and forget" of some code, but still want to ensure that my memory is cleaned up (per Why does asynchronous delegate method require calling EndInvoke?), will the following achieve that goal?
Action myAction = () => LongRunTime();
myAction.BeginInvoke(myAction.EndInvoke,null);
I've looked around but haven't seen that pattern used anywhere. Rather, people use an annonomoyus method as their callback (such as The proper way to end a BeginInvoke?) or they define an actual callback method. Since I haven't seen anyone else do this, it makes me think it either doesn't work or is otherwise a bad idea.
Thanks!
Using a method group conversion instead of a delegate is fine, the
EndInvoke
will still be called in on yourAction
. There is nothing else to be done, since this is a fire and forget call.Unfortunately, it's somewhat hard to directly irrefutably prove that EndInvoke is called, since
Action
is a delegate and we can't just add a breakpoint on some class in the BCL.This code will (periodically) inspect some private field of the IAsyncResult that is returned by
BeginInvoke
, which seems to keep track of whether or notEndInvoke
has been called yet:I've double checked using SOS that there aren't any managed memory leaks. I've also tried several other proofs, but they were more circumstantial than this one, I think.
Some interesting I discovered during my investigation: the
myAction.BeginInvoke
call will show up on profilers using instrumentation, butmyAction.EndInvoke
does not.Nowdays it could be done like