每个 BeginInvoke 后面都必须跟一个 EndInvoke 吗?
MS 文档中的此页面,涵盖 Windows 窗体应用程序中的异步,状态:
如果需要,您可以调用 EndInvoke 从委托检索返回值,但这不是必需的。(已添加强调)
此页面涵盖了异步委托的一般情况,说明了一些不同的内容:
无论您使用哪种技术,始终调用 EndInvoke 来完成异步调用。
这两者似乎存在直接冲突。
哪个是真的?有人可以解释一下吗?
另请参阅 Phil Haack 的帖子。
This page in the MS documentation, covering asynchrony in Windows Forms applications, states:
You can call EndInvoke to retrieve the return value from the delegate, if neccesary, but this is not required. (emphasis added)
This page covering the general case of asynchronous delegates, states something different:
No matter which technique you use, always call EndInvoke to complete your asynchronous call.
These two seem to be in direct conflict.
Which is true? Can someone explain?
see also, a post by Phil Haack.
Related: Is EndInvoke optional, sort-of optional, definitely not optional?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除非接口文档明确说明,否则您必须为调用 BeginInvoke 的每个位置调用 EndInvoke。主要原因是 EndInvoke 是所有者可以安全释放可能为 BeginInvoke 调用分配的某些资源(例如 WaitHandle)的唯一时间。
但这条规则也有例外。 Control.BeginInvoke 等 API 不需要 EndInvoke,但文档中对此有明确说明。
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.
两者都是正确的——它们是不同的称呼。
一般,您应该始终调用
EndInvoke
以确保释放异步调用获取的任何资源。但是,Windows 窗体团队保证您不需要对
Control.Invoke
执行此操作。不过,您可能很需要为ISynchronizeInvoke
的其他实现执行此操作。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 ofISynchronizeInvoke
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:
Either way, the application continues uninterrupted.