I have done a lot of reading about Control.Invoke and Control.BeginInvoke and understand that Invoke is like SendMessage() and BeginInvoke is like PostMessage(), but I do not understand where the parameter list passed via new object[] { arg, arg, arg, ...} is stored. During a conventional call, parameters are pushed to the stack and popped within the called function, then the call frame is recovered from the stack after exit, I assume releasing any references to any heap objects, allowing them to be collected. So, where is the pushed stack date for Invoke/BeginInvoke stored? How does it get disposed once the method called exits?
Also, I have successfully invoked a control method without loading a new object array with the pass parameters. Why would this work? Better yet, since it does work, why would all the examples I have ever seen show it with a new object array?
This is what I have always seen and used:
BeginInvoke(FormReceiveEvent, new object[] { Event, Arg1, Arg2, Arg3 });
But this works too:
BeginInvoke(FormReceiveEvent, Event, Arg1, Arg2, Arg3);
Any information and comments are always appreciated…
Thanks in advance.
The
object[]containing the parameters is stored internally by the BeginInvoke method while it asynchronously invokes the target delegate. The reference to the array is released once the asynchronous call completes, allowing the array and its contents (assuming they are not otherwise reachable) to be collected.The
BeginInvoke(FormReceiveEvent, Event, Arg1, Arg2, Arg3);form works because the second parameter toBeginInvokeis defined asparams object[]. This means that if you don’t explicitly create an array, the compiler will do it for you. Therefore, the two calls are identical in terms of runtime behaviour.A note on terminology: in the context of .Net, to say that an object is "disposed" typically means that the object implements
IDisposableand that itsIDisposable.Disposemethod got called. In the context ofControl.BeginInvokeandControl.Invoke, that does not happen.After the asynchronous call finishes, the reference to the
object[]is released so it can be collected, but if any of its members implementIDisposable, theIDisposable.Disposemethod is not called. The object’s resources will not be released until it is collected (or someone else disposes it).