0

I'm trying to execute a Task with a timeout. But, when the task expires, it continue executing in a thread and I want to cancel it. This is part of the code:

var task = Task.Run(() => DoMethod());
if (task.Wait(TimeSpan.FromSeconds(timeout)))
   result = task.Result;
return result;

I read about CancellationToken, but I don´t know how to implement it.

enriquesroman
  • 15
  • 1
  • 4
  • Run 2 tasks, `WaitAny`. – Sinatr Oct 17 '16 at 14:47
  • 1
    Short answer: no. Long answer: change `DoMethod()` so that it does support cancellation, see [duplicate](http://stackoverflow.com/questions/4359910/is-it-possible-to-abort-a-task-like-aborting-a-thread-thread-abort-method). – CodeCaster Oct 17 '16 at 14:48
  • 1
    @Dmitry [_"Cancellation is cooperative and is not forced on the listener. The listener determines how to gracefully terminate in response to a cancellation request"_](http://stackoverflow.com/questions/22637642/using-cancellationtoken-for-timeout-in-task-run-does-not-work) – CodeCaster Oct 17 '16 at 14:51
  • Extra reading from the MSDN: "[Cancellation in Managed Threads](https://msdn.microsoft.com/en-us/library/dd997364(v=vs.110).aspx)" – Scott Chamberlain Oct 17 '16 at 14:59

0 Answers0