Using CancellationToken for timeout in Task.Run does not work
Solution 1
Cancellation in Managed Threads:
Cancellation is cooperative and is not forced on the listener. The listener determines how to gracefully terminate in response to a cancellation request.
You didn't write any code inside your Task.Run
method to access your CancellationToken
and to implement cancellation - so you effectively ignored the request for cancellation and ran to completion.
Solution 2
There is a difference in canceling a running task, and a task scheduled to run.
After the call to the Task.Run method, the task is only scheduled, and probably have not been executed yet.
When you use the Task.Run(..., CancellationToken) family of overloads with cancellation support, the cancellation token is checked when the task is about to run. If the cancellation token has IsCancellationRequested set to true at this time, an exception of the type TaskCanceledException is thrown.
If the task is already running, it is the task's responsibility to call the ThrowIfCancellationRequested method, or just throw the OperationCanceledException.
According to MSDN, it's just a convenience method for the following:
if (token.IsCancellationRequested) throw new OperationCanceledException(token);
Note the different kind of exception used in this two cases:
catch (TaskCanceledException ex)
{
// Task was canceled before running.
}
catch (OperationCanceledException ex)
{
// Task was canceled while running.
}
Also note that TaskCanceledException
derives from OperationCanceledException
, so you can just have one catch
clause for the OperationCanceledException
type:
catch (OperationCanceledException ex)
{
if (ex is TaskCanceledException)
// Task was canceled before running.
// Task was canceled while running.
}
Solution 3
I think because you're not invoking the method ThrowIfCancellationRequested()
from your CancellationToken object.
You're ignoring, in this way, the request for the cancellation of the task.
You should do something like this:
void Main()
{
var ct = new CancellationTokenSource(500).Token;
var v =
Task.Run(() =>
{
Thread.Sleep(1000);
ct.ThrowIfCancellationRequested();
return 10;
}, ct).Result;
Console.WriteLine(v); //now a TaskCanceledException is thrown.
Console.Read();
}
The second variant of your code works, because you're already initializing a token with a Canceled
state set to true. Indeed, as stated here:
If canceled is true, both CanBeCanceled and IsCancellationRequested will be true
the cancellation has already been requested and then the exception TaskCanceledException
will be immediately thrown, without actually starting the task.
Solution 4
Another implementation using Task.Delay with token instead it Thread.Sleep.
static void Main(string[] args)
{
var task = GetValueWithTimeout(1000);
Console.WriteLine(task.Result);
Console.ReadLine();
}
static async Task<int> GetValueWithTimeout(int milliseconds)
{
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
cts.CancelAfter(milliseconds);
token.ThrowIfCancellationRequested();
var workerTask = Task.Run(async () =>
{
await Task.Delay(3500, token);
return 10;
}, token);
try
{
return await workerTask;
}
catch (OperationCanceledException )
{
return 0;
}
}
Aliostad
"For when I am weak then I am strong" Solution Architect, computer vision enthusiast (published a few papers, demo here) and ex-medical doctor. Working mainly as a middleware specialist with interests from CLR level details and protocols up to UI level (WPF and HTML+jquery). Love to be able to help... My one liner: "My washing machine will talk REST+JSON in 5 years..." [I said this back in 2010] UPDATE Marissa Mayer approved my prediction. Follow me on twitter: @aliostad
Updated on November 25, 2021Comments
-
Aliostad over 2 years
OK, my questions is really simple. Why this code does not throw
TaskCancelledException
?static void Main() { var v = Task.Run(() => { Thread.Sleep(1000); return 10; }, new CancellationTokenSource(500).Token).Result; Console.WriteLine(v); // this outputs 10 - instead of throwing error. Console.Read(); }
But this one works
static void Main() { var v = Task.Run(() => { Thread.Sleep(1000); return 10; }, new CancellationToken(true).Token).Result; Console.WriteLine(v); // this one throws Console.Read(); }
-
Aliostad about 10 yearsplease see updated question - If it is cooperative, why second one works?
-
Darrel Miller about 10 yearsThe CancellationTokenSource is setup with a timeout. If Task.Delay is used instead of Thread.Sleep you can get the exception to throw.
-
Damien_The_Unbeliever about 10 years@Aliostad -
Tasks
may sit waiting to be scheduled for any amount of time before their code actually runs. An obvious optimization, for a task that has been provided with a cancellation token, is to check that token before you actually schedule the task on a thread. In your second case, when that check is performed, cancellation has already been requested so the task is never actually started. -
Aliostad about 10 years@Damien_The_Unbeliever makes sense.
-
Zhiliang over 6 yearsBut what's the point of passing ct to Task.Run?
-
Alberto Solano over 6 years@Zhiliang Are you familiar with TPL? The "ct" variable is passed to Task.Run to be able to cancel the task. In this case, the above user asked why his code didn't throw any exception using a CancellationToken that would be cancelled after 500 ms. The reason is that the code didn't do anything to deal with cancellation.
-
Zhiliang over 6 yearsSince
ct.ThrowIfCancellationRequested();
actually references thect
variable in the closure, I can get the same result if I ommit thect
that is passed toTask.Run()
. Right? -
Alberto Solano over 6 years@Zhiliang Yes, you can get the same result (exception thrown), although this means your task will not have cancellation support. The code snippet you see in my answer was simply copied and pasted from the question, and accordingly modified just to show what asked in the question, not caring too much about 100% "perfect" code.
-
Karata about 6 yearsAlso have the question: What's the difference for Task.Run(task, cancel) vs Task.Run(task)? The ct variable is passed to Task.Run, but does not seem to be in use anywhere.
-
Alberto Solano about 6 years@Karata The difference is explained in the documentation about Task.Run and its overloads. Passing ct (or CancellationToken) to Task.Run, we're saying that we want to cancel the task returned from Task.Run.
-
Jim about 3 yearsPassing ct will auto cancel the task before it started. If not, you should check the ct status in the code, and the task is running.