Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous Invoking - Is EndInvoke required? [duplicate]

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 =)

like image 380
William Lawn Stewart Avatar asked Jun 30 '11 04:06

William Lawn Stewart


3 Answers

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

like image 120
David Karlaš Avatar answered Nov 14 '22 22:11

David Karlaš


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.

like image 32
Dan Bryant Avatar answered Nov 14 '22 23:11

Dan Bryant


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); 
like image 39
Sean Thoman Avatar answered Nov 15 '22 00:11

Sean Thoman