只需要'最近'的任务 - 取消/忽略的最佳做法?

use*_*225 5 c# multithreading task c#-4.0

我的任务看起来像这样:

var task = Task.Factory.StartNew <object>(LongMethod);
task.ContinueWith(TaskCallback, TaskScheduler.FromCurrentSynchronizationContext());
Run Code Online (Sandbox Code Playgroud)

LongMethod调用一个长期运行的服务,在此期间我不能(或者至少不认为我可以),不断轮询取消令牌以查看它是否已被取消.但是,我有兴趣'取消'或忽略回调方法.

当调用TaskCallback时,我只对'结果'感兴趣,如果它来自最近的任务(让我们假设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
}
Run Code Online (Sandbox Code Playgroud)

我很确定这不是"最佳实践"解决方案.但是什么呢?传递和维护取消令牌也不是那么优雅.

Dou*_*las 6

我个人觉得以下方法是最优雅的:

// 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
}
Run Code Online (Sandbox Code Playgroud)