Only need 'most recent' Task - best practices for cancelling/ignoring?

前端 未结 2 585
广开言路
广开言路 2021-02-10 01:50

I have a task that looks like this:

var task = Task.Factory.StartNew (LongMethod);
task.ContinueWith(TaskCallback, TaskScheduler.FromCurrentSynchro         


        
      
      
      
2条回答
  •  猫巷女王i
    2021-02-10 02:29

    I personally find the following approach to be the most elegant:

    // 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(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 task)
    {
        // Just update UI
    }
    
        

    提交回复
    热议问题