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

前端 未结 2 578
广开言路
广开言路 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条回答
  •  北荒
    北荒 (楼主)
    2021-02-10 02:18

    I understand that you cannot cancel your long running task but want the process to be instantly aborted from the users point of view when he cancels.

    Start a cancel task in parallel with your long running task. Continue off of Task.WhenAny(longRunningTask, cancelTask) and check, if the completed task was the long running task or the cancel task. You can then decide what to do (show results or update UI).

    When you cancel the "cancel task" the continuation will instantly fire.

提交回复
热议问题