我有一个看起来像这样的任务:
var task = Task.Factory.StartNew <object>(LongMethod);
task.ContinueWith(TaskCallback, TaskScheduler.FromCurrentSynchronizationContext());
LongMethod 调用一个长时间运行的服务,在此期间我不能(或者至少我认为我不能)不断轮询取消令牌以查看它是否已被取消。但是,我对“取消”或忽略回调方法感兴趣。
当任务回调被调用时,我只对“结果”感兴趣if它来自最近的任务(让我们假设 LongMethod 调用的服务保留顺序,并且还假设用户可以多次单击该按钮,但只有最新的一个是相关的)。
我按以下方式修改了代码:创建任务后,将其添加到堆栈顶部。在 TaskCallback 中,我检查传递给回调的任务是否是最新的任务(即堆栈顶部的 TryPeek)。如果不是,我就忽略结果。
private ConcurrentStack<Task> _stack = new ConcurrentStack<Task>();
private void OnClick(object sender, ItemClickEventArgs e)
{
var task = Task.Factory.StartNew < object >( LongMethod);
task.ContinueWith(TaskCallback, TaskScheduler.FromCurrentSynchronizationContext());
_stack.Push(task);
}
private void TaskCallback(Task<object> task)
{
Task topOfStack;
if(_stack.TryPeek(out topOfStack)) //not the most recent
{
if (task != topOfStack) return;
}
//else update UI
}
我非常确定这不是一个“最佳实践”解决方案。但什么是?传递和维护取消令牌似乎也不是那么优雅。
我个人认为以下方法是最优雅的:
// Cancellation token for the latest task.
private CancellationTokenSource cancellationTokenSource;
private void OnClick(object sender, ItemClickEventArgs e)
{
// If a cancellation token already exists (for a previous task),
// cancel it.
if (this.cancellationTokenSource != null)
this.cancellationTokenSource.Cancel();
// Create a new cancellation token for the new task.
this.cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = this.cancellationTokenSource.Token;
// Start the new task.
var task = Task.Factory.StartNew<object>(LongMethod, cancellationToken);
// Set the task continuation to execute on UI thread,
// but only if the associated cancellation token
// has not been cancelled.
task.ContinueWith(TaskCallback,
cancellationToken,
TaskContinuationOptions.NotOnCanceled,
TaskScheduler.FromCurrentSynchronizationContext());
}
private void TaskCallback(Task<object> task)
{
// Just update UI
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)