为什么要异步回调?
我读到,AsyncCallback
函数将在委托调用完成后执行所有后处理任务。我的问题是在 EndInvoke
之后/之下编写后处理任务有什么区别,因为 EndInvoke
将等待委托调用返回。
I have read that the AsyncCallback
function will do all the post processing tasks after a delegate call completes. My question is what is the difference of writing the post processing tasks after/below EndInvoke
, as EndInvoke
will wait until the delegate call returns.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用委托的 BeginInvoke() 方法的要点是目标将异步运行。如果您在 BeginInvoke() 之后立即调用 EndInvoke(),则不再有任何使用它的意义。通过直接调用委托,您将获得完全相同的行为,减去开销和线程问题。
该值是在目标方法完成后立即异步获取回调。只有然后调用EndInvoke(),它会立即完成。这会清理系统资源,并在目标方法抛出异常时重新抛出异常。不要按照已投票答案中的建议跳过调用 EndInvoke() ,您将泄漏资源至少 10 分钟。
The point of using a delegate's BeginInvoke() method is that the target will run asynchronously. If you call EndInvoke() right after BeginInvoke() then there is no longer any point in using it. You'll get the exact same behavior by simply calling the delegate directly, minus the overhead and the threading headaches.
The value is getting the callback when the target method completes, asynchronously right after it does. Only then call EndInvoke(), it completes immediately. That cleans up the system resources and re-throws an exception when the target method threw one. Do not skip calling EndInvoke() as suggested in the upvoted answer, you'll leak the resources for at least 10 minutes.
您可以选择根本不调用 EndInvoke,而仅依赖回调。这样,启动就来自委托本身,而不是您,并且您不必决定调用何时完成。
You could choose not to invoke EndInvoke at all and only rely on the callback. This way the initiation comes from the delegate itself and not from you, and you dont have to decide when the invocation will complete.