是否存在推荐建立的自我取消和重新启动任务的模式?自我取消和重新启动任务的模式
例如,我正在开发背景拼写检查程序的API。拼写检查会议包装为Task
。每个新会话都应该取消前一个会话并等待终止(正确地重新使用拼写检查服务提供程序等资源)。
我想出这样的事情:
class Spellchecker
{
Task pendingTask = null; // pending session
CancellationTokenSource cts = null; // CTS for pending session
// SpellcheckAsync is called by the client app
public async Task<bool> SpellcheckAsync(CancellationToken token)
{
// SpellcheckAsync can be re-entered
var previousCts = this.cts;
var newCts = CancellationTokenSource.CreateLinkedTokenSource(token);
this.cts = newCts;
if (IsPendingSession())
{
// cancel the previous session and wait for its termination
if (!previousCts.IsCancellationRequested)
previousCts.Cancel();
// this is not expected to throw
// as the task is wrapped with ContinueWith
await this.pendingTask;
}
newCts.Token.ThrowIfCancellationRequested();
var newTask = SpellcheckAsyncHelper(newCts.Token);
this.pendingTask = newTask.ContinueWith((t) => {
this.pendingTask = null;
// we don't need to know the result here, just log the status
Debug.Print(((object)t.Exception ?? (object)t.Status).ToString());
}, TaskContinuationOptions.ExecuteSynchronously);
return await newTask;
}
// the actual task logic
async Task<bool> SpellcheckAsyncHelper(CancellationToken token)
{
// do not start a new session if the the previous one still pending
if (IsPendingSession())
throw new ApplicationException("Cancel the previous session first.");
// do the work (pretty much IO-bound)
try
{
bool doMore = true;
while (doMore)
{
token.ThrowIfCancellationRequested();
await Task.Delay(500); // placeholder to call the provider
}
return doMore;
}
finally
{
// clean-up the resources
}
}
public bool IsPendingSession()
{
return this.pendingTask != null &&
!this.pendingTask.IsCompleted &&
!this.pendingTask.IsCanceled &&
!this.pendingTask.IsFaulted;
}
}
的客户端应用程序(用户界面),就应该能够调用SpellcheckAsync
多次需要,而不必担心取消挂起的会话。主要的doMore
循环在UI线程上运行(因为它涉及UI,而所有拼写检查服务提供者调用都是IO绑定的)。
我觉得有点不舒服,因为我不得不将API分成两个版本,分别是SpellcheckAsync
和,但我想不出一个更好的方法来做到这一点,它还有待测试。
@Stephen Cleary,我非常尊重你在所有异步事物上的工作,所以请不要误以为这是我的好奇心。我有些惊讶,你没有用'SemaphoreSlim'或你自己的'AsyncLock'或类似的东西重写'await this.pendingTask'部分。您是否一般认为提高异步方法的“同步”部分中的线程安全性是一个过早的优化? –
@KirillShlenskiy:使用“SemaphoreSlim”或其他类似的东西来限制每次一次的限制没有任何问题。 –