Possible Duplicates:
Must every BeginInvoke be followed by an EndInvoke?
Is EndInvoke() optional, sort-of optional, or definitely not optional?
I've got a multithreaded application, and one of the secondary threads needs to get some code to execute on the main thread once every couple of minutes. There isn't any return value, and the second thread doesn't care if it raises any exceptions or fails to run.
So far, I've been getting it to run the code via Form.Invoke
, but it sometimes takes much longer than usual (a couple of seconds) and blocks the thread until it completes. I need the second thread to be able to continue execution without stalling for several seconds.
BeginInvoke
sounds like it'd do the job nicely, but I don't really have anywhere to call EndInvoke
, since I don't want to wait for it or get a return value. And considering that the code being invoked involves a bunch of native calls, I'm not sure if its a good idea to not EndInvoke
.
Do I need to call EndInvoke
at all, or is there some other way of getting code to run on the main form thread asyncronously that I should be using instead?
Thanks =)
You can call EndInvoke to retrieve the return value from the delegate, if neccesary, but this is not required. EndInvoke will block until the return value can be retrieved.
Source:http://msdn.microsoft.com/en-us/library/0b1bf3y3.aspx under Remarks
One typical way to call EndInvoke is by including a completion callback with the BeginInvoke so that you can call EndInvoke in the callback. This is more important for Begin/End methods that do something more specific than Invoke, such as BeginRead/EndRead; in the latter cases, the End may be required for cleanup and will also typically (re)throw any Exception that occurred during the process.
You should ensure that EndInvoke is called, but you can do it pretty easily, something like:
var action = new Action(SomeMethodGroup);
action.BeginInvoke(new AsyncCallback(
x => (x.AsyncState as Action).EndInvoke(x)), action);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With