图案暂停/恢复异步任务吗? [英] A pattern to pause/resume an async task?

查看:204
本文介绍了图案暂停/恢复异步任务吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主要的IO绑定连续任务(后台拼写检查跟一个拼写检查服务器)。有时,这个任务需要被搁置,后来重新开始时,根据用户的活动。

I have a mostly IO-bound continuous task (a background spellchecker talking to a spellcheck server). Sometimes, this task needs to be put on hold and resumed later, depending on the user activity.

虽然暂停/恢复本质上是什么异步/计谋确实,我发现很少谈到如何实现实际的暂停/播放逻辑异步方法。 有没有推荐的图案呢?

While suspend/resume is essentially what async/await does, I've found little information on how to implement the actual pause/play logic for an asynchronous method. Is there a recommended pattern for this?

下面是什么,我想出了一个初始版本。我们的想法是通过翻转 TaskCompletionSource 任务每次暂停和恢复请求。它的工作原理,但似乎有点拗口,无法读取。我也看了一下用斯蒂芬Toub的 AsyncManualResetEvent 这一点,但认为它可能是矫枉过正。

Here is an initial version of what I've come up with. The idea is to flip tasks via TaskCompletionSource for each pause and resume request. It works, but appears to be a bit mouthful and unreadable. I've also looked at using Stephen Toub's AsyncManualResetEvent for this, but thought it might be an overkill.

[更新] 下面是一个改进版本,根据@ svick的建议。

[UPDATE] Here is an improved version, based upon @svick's suggestion.

推荐答案

AsyncManualResetEvent 正是你所需要的,考虑如何凌乱你目前的code是。但稍微更好的解决方案将是使用从斯蒂芬Toub另一种方法: PauseToken 。它的工作原理类似于 AsyncManualResetEvent ,但它的接口就是为此而特别制作。

AsyncManualResetEvent is exactly what you need, considering how messy your current code is. But a slightly better solution would be to use another approach from Stephen Toub: PauseToken. It works similarly to AsyncManualResetEvent, except its interface is made specifically for this purpose.

这篇关于图案暂停/恢复异步任务吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆