开发者

Asynchronous Invoking - Is EndInvoke required? [duplicate]

This question already has answers here: Closed 11 years ago.

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 n开发者_如何学Cicely, 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); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜