async/await 取消机制
我有一个问题,关于可以使用什么机制来取消正在进行的异步操作,而不是使用异步/等待上下文中的取消令牌。我确信这是一个经过充分研究的设计决策,考虑到了语言的命令性,但在实际情况下,必须将取消对象传递给所有异步方法至少有点痛苦。 c#社区还有另外的设计思路,或者提出的取消机制就可以了?我想我错过了一些东西。
I have a question about what mechanism to cancel an ongoing async operation could be used, instead a cancellation token in the async/await context. I'm sure this is a well studied design decision that takes into account the imperative nature of the language, but in real situations having to pass a cancellation object to all your async methods is, at least, a bit painful. There are another design ideas from the c# community, or the proposed cancellation mechanism is just OK? I think I'm missing something.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
取消令牌是最佳实践,特别是当异步过程成本高昂、没有预设结束条件或涉及外部资源时。
但是,如果您愿意,您可以简单地“放弃”。不是告诉异步线程中止处理并清理,而是“超时”;停止等待它完成,分离所有侦听器,然后继续运行。当线程最终完成时,它将检查其事件,意识到没有人在监听,然后默默地终止。好处是简单,但是在很多情况下这将是一件坏事:
The cancellation token is the best practice, especially when the asynchronous process is expensive, has no preset ending condition, or involves external resources.
However, you can, if you wish, simply "give up". Instead of telling the async thread to abort processing and clean up, just "time out"; stop waiting for it to complete, detach any listeners, and keep running. When the thread eventually does complete, it'll check its event, realize nobody's listening, and silently terminate. The upside is the simplicity, however there are many situations in which this would be a BAD thing:
为了使异步操作的取消有意义,该操作必须执行谨慎的步骤,因为该操作需要检查取消令牌并停止自身继续。即,取消令牌仅仅是要实现的模式,而不是异步/等待机制。
这意味着,如果您的异步操作只是一个带有完成句柄的 I/O 调用,那么您最好放弃而不是取消,因为在该调用返回之前,该操作将没有机会检查您的令牌到那时就什么也得不到了。
因此,在考虑取消令牌时,首先考虑是否可以通过支持取消来提高此操作的效率,或者是否只是不等待它完成(即使用超时机制)更有意义。
In order for cancellation of an async operation to make sense, that operation must perform discreet steps, since it is up the operation to check the cancellation token and stop itself from continuing. I.e. the cancellation token is merely a pattern to be implemented not a mechanism of async/await.
What that means it that if your async operation is just one I/O call with a completion handle, you might as well, just give up rather than cancel, since the operation will not have the oppurtunity to check your token until that call comes back at which point there is nothing to be gained.
So when considering a cancellation token, first consider whether this operation can be made more efficient by supporting cancellation or whether just not waiting for it to complete (i.e. using a timeout mechanism instead) makes more sense.