Search code examples
c#.net-4.0timeouttaskcancellation

Cancelling a already running task


I have timoeut between two tasks implemented as follows. If timeoutTask completes first, I would like to cancel ( or kill ) the workerTask, Is there anyway of doing this?

var timeoutTask = Task.Delay(1500);

var workerTask = Task.Run(() => { ThirdPartLibraryAPI.Run() });
var taskThatCompletedFirst = await Task.WhenAny(timeoutTask, workerTask);

        //stuff to do on timeout can be done here
if (taskThatCompletedFirst == timeoutTask)
{
  // At this point workerTask is still running.
  // how can i cancel or kill this task  
}

Solution

  • This is only possible if the third party library specifically provides support for cancellation. If it does, you'll need to use whatever tools it exposes (there are any number of ways of supporting it) to cancel the operation.

    If it doesn't natively support cancellation, then the best you can do is what you're doing, which is having your program continue executing despite the fact that the operation hasn't completed.