问题描述
我已经阅读了几个论坛,甚至一两个 stackoverflow 问题都说在使用 Delegate.BeginInvoke 时必须使用 Delegate.EndInvoke.我读过的很多关于使用 BeginInvoke 的文章都没有提到使用 EndInvoke.此外,我仅使用 BeginInvoke 部署了生产代码,似乎没有任何内存问题.我使用 BeginInvoke 的方式通常是处理线程,我不关心它们何时完成或处理需要多长时间.
I've read a couple of forums and even a stackoverflow question or two saying that Delegate.EndInvoke is necessary when using Delegate.BeginInvoke. Many of the articles I've read talking about using BeginInvoke have failed to mention using EndInvoke. Also I've deployed production code using only BeginInvoke and there doesn't appear to be any memory issues. The way I've used BeginInvoke is generally with threads that I don't care about when they finish or how long they take to process.
推荐答案
来自 MSDN 文章 '异步调用同步方法':
From the MSDN article 'Calling Synchronous Methods Asynchronously':
无论您使用哪种技术,总是调用 EndInvoke 来完成你的异步调用.
No matter which technique you use, always call EndInvoke to complete your asynchronous call.
现在,有理论,然后有实践.您已经发现,就像您之前的许多其他开发人员一样,您通常可以忽略这个记录在案的要求而侥幸成功.EndInvoke
是否真的做了任何绝对必要的事情来防止你的应用程序崩溃、内存泄漏等,这可能是一个实现细节.但事情是这样的:如果这是一个文档化的要求,你真的应该去做.这不仅仅是理论.这是为了在发生变化时保护自己.
Now, there is theory and then there is practice. You have found, like many other developers before you, that you can often get away with ignoring this documented requirement. It may be an implementation detail whether EndInvoke
actually does anything that's absolutely necessary to prevent your application from crashing, leaking memory, etc. But here's the thing: if it's a documented requirement, you really ought to do it. This is not just about theory; it's about protecting yourself in the event of change.
通过记录这个要求,这个异步调用机制的设计者基本上可以自由地改变 BeginInvoke
和 EndInvoke
的工作方式,这样,如果有如果有充分的理由(例如,性能增强),EndInvoke
可能会突然变得更加必要.假设如果你忘记它会突然导致死锁.他们已经通过说总是调用EndInvoke
来掩饰自己;如果您的应用因您未遵守此要求而停止运行,那么您有责任.
By documenting this requirement, the designers of this asynchronous calling mechanism basically gave themselves the freedom to change the way BeginInvoke
and EndInvoke
work down the line so that, if there were sufficient reason (e.g., a performance enhancement), EndInvoke
could suddenly become a lot more necessary. Suppose it would suddenly result in a deadlock if you forgot it. They've already covered themselves by saying always call EndInvoke
; if your app stops working because you didn't follow this requirement, the onus is on you.
我并不是说这必然是一种可能的情况.我的观点很简单,你不应该——或者至少我不会——问这真的有必要吗?"怀着如果我能侥幸把它排除在外,那么我会的心态,因为它已证明你应该这样做.
I'm not saying this is necessarily a likely scenario. My point is simply that you shouldn't—or at least I wouldn't—ask "Is this really necessary?" with the mindset of If I can get away with leaving it out, then I will, since it is documented that you should do it.
这篇关于Delegate.EndInvoke() 真的有必要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!