0

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  
}
whoami
  • 1,689
  • 3
  • 22
  • 45

1 Answers1

1

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • So there is no native Task.Cancel type of API that I can use? Problem is if timeout value is small, workerTask will complete in future and I don't know how to handle that scenario. – whoami Jan 13 '15 at 21:00
  • 2
    @johnsmith It's impossible for `Task` to support it in the general case. The underlying operation representing the task can be just about anything; there's no way to cancel any unknown operation. Different types of actual operations will provide cancellation support very differently. – Servy Jan 13 '15 at 21:01
  • 1
    You can only cancel *your* task using a CancellationToken. For the remote task, if the 3rd party doesnt provide a way to cancel the task, you can check if there is a compensating task that you can perform to undo the initial task. – sudheeshix Jan 13 '15 at 21:03
  • @Servy I can understand that but I was thinking if there is something equivalent to Thread.Abort in Task world. – whoami Jan 13 '15 at 21:08
  • 1
    @johnsmith `Thread.Abort` doesn't even reliably work, and is just *filled* with tons of pitfalls. It's considered obsolete as an operation. It's no surprise at all that `Task` wouldn't try to shoe in an already broken feature into a context in which it doesn't even apply a huge percentage of the time. – Servy Jan 13 '15 at 21:11