Must every BeginInvoke be followed by an EndInvoke?

我是研究僧i 提交于 2019-11-27 21:09:00

Unless the documentation for an interface explicitly says otherwise you must call EndInvoke for every place you call BeginInvoke. The primary reason is that EndInvoke is the only time where the owner can safely free certain resources that may be allocated for the BeginInvoke call (such as a WaitHandle).

But there are exceptions to this rule. APIs such as Control.BeginInvoke do not require an EndInvoke but it's explicit in the documentation.

Both are true - they're different calls.

In general you should always call EndInvoke to ensure that any resources acquired by the asynchronous call are released.

However, the Windows Forms team has guaranteed that you don't need to do this for Control.Invoke. You may well need to do it for other implementations of ISynchronizeInvoke though.

I've used the fire-and-forget method with delegates before where the results were "useful if available, but not required". Just remember that you have no completion guarantees with that method. In particular, here's one place that I use it:

  • Start a delegate to check for application updates
  • Delegate begins a web request with a timeout
  • If an error/timeout occurs, or if the application is up-to-date, the method simply returns
  • If the application is out of date, I place a non-focus-stealing systray message stating so (no systray icon unless the update is available)

Either way, the application continues uninterrupted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!