Questions tagged [cancellationtokensource]

Provides a cancellation token in .NET for cooperative cancellation of asynchronous or long-running synchronous operations.

Provides a cancellation token in NET. Starting with .NET Framework 4.0, the .NET Framework uses a unified model for cooperative cancellation of asynchronous or long-running synchronous operations that involves two objects:

  • A CancellationTokenSource object, which provides a cancellation token through its Token property and sends a cancellation message by calling its Cancel or CancelAfter method.
  • A CancellationToken object, which indicates whether cancellation is requested.

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.Token property. You then pass the cancellation token to any number of threads, tasks, or operations that should receive notice of cancellation. The token cannot be used to initiate cancellation. When the owning object calls CancellationTokenSource.Cancel, the IsCancellationRequested property on every copy of the cancellation token is set to true. The objects that receive the notification can respond in whatever manner is appropriate.

References

359 questions
210
votes
7 answers

When to dispose CancellationTokenSource?

The class CancellationTokenSource is disposable. A quick look in Reflector proves usage of KernelEvent, a (very likely) unmanaged resource. Since CancellationTokenSource has no finalizer, if we do not dispose it, the GC won't do it. On the other…
172
votes
5 answers

Why CancellationToken is separate from CancellationTokenSource?

I'm looking for a rationale of why .NET CancellationToken struct was introduced in addition to CancellationTokenSource class. I understand how the API is to be used, but want to also understand why it is designed that way. I.e., why do we have: var…
96
votes
5 answers

How to cancel a CancellationToken

I start a task, that starts other tasks and so forth. Given that tree, if any task fails the result of the whole operation is useless. I'm considering using cancellation tokens. To my surprise, the token does not have a "CancelThisToken()"…
Leonardo
  • 10,737
  • 10
  • 62
  • 155
76
votes
3 answers

How to reset a CancellationToken properly?

I have been playing round with the Async CTP this morning and have a simple program with a button and a label. Click the button and it starts updating the label, stop the button it stops writing to the label. However, I'm not sure how to reset the…
76
votes
4 answers

Linking Cancellation Tokens

I use a cancellation token that is passed around so that my service can be shut down cleanly. The service has logic that keeps trying to connect to other services, so the token is a good way to break out of these retry loops running in separate…
Retrocoder
  • 4,483
  • 11
  • 46
  • 72
76
votes
5 answers

How to "sleep" until timeout or cancellation is requested in .NET 4.0

What's the best way to sleep a certain amount of time, but be able to be interrupted by a IsCancellationRequested from a CancellationToken? I'm looking for a solution which works in .NET 4.0. I'd like to write void MyFunc (CancellationToken ct) { …
Onur
  • 5,017
  • 5
  • 38
  • 54
61
votes
4 answers

Using CancellationToken for timeout in Task.Run does not work

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; …
40
votes
3 answers

How to combine TaskCompletionSource and CancellationTokenSource?

I have such code (simplified here) which awaits finishing task: var task_completion_source = new TaskCompletionSource(); observable.Subscribe(b => { if (b) task_completion_source.SetResult(true); }); await…
35
votes
3 answers

Cancelling an HttpClient Request - Why is TaskCanceledException.CancellationToken.IsCancellationRequested false?

Given the following code: var cts = new CancellationTokenSource(); try { // get a "hot" task var task = new HttpClient().GetAsync("http://www.google.com", cts.Token); // request cancellation cts.Cancel(); await task; //…
Todd Menier
  • 37,557
  • 17
  • 150
  • 173
28
votes
5 answers

How to reset the CancellationTokenSource and debug the multithread with VS2010?

I have used CancellationTokenSource to provide a function so that the user can cancel the lengthy action. However, after the user applies the first cancellation, the later further action doesn't work anymore. My guess is that the status of…
q0987
  • 34,938
  • 69
  • 242
  • 387
27
votes
6 answers

TaskCanceledException when calling Task.Delay with a CancellationToken in an keyboard event

I am trying to delay the processing of a method (SubmitQuery() in the example) called from an keyboard event in WinRT until there has been no further events for a time period (500ms in this case). I only want SubmitQuery() to run when I think the…
24
votes
1 answer

CancellationTokenSource vs. volatile boolean

Are there any benefits for using a CancellationTokenSource over a volatile boolean field for signalling a Task to finish?
Yoav
  • 3,326
  • 3
  • 32
  • 73
22
votes
2 answers

Any way to differentiate Cancel and Timeout

I have some code that is validating some data by making calls to a number of other services. I start all of the calls in parallel and then wait until at least one of them finishes. If any of the requests fail, I don't care about the result of the…
20
votes
3 answers

How to attach CancellationTokenSource to DownloadStringTaskAsync method and cancel the async call?

I an creating a sample example to call link using WebClient using async and await method now I want to attach cancel async call functionality also. But I am not able to get CancellationTokenSource token and attach DownloadStringTaskAsync to this…
Balraj Singh
  • 3,381
  • 6
  • 47
  • 82
19
votes
1 answer

Canceling SQL Server query with CancellationToken

I have a long-running stored procedure in SQL Server that my users need to be able to cancel. I have written a small test app as follows that demonstrates that the SqlCommand.Cancel() method works quite nicely: private SqlCommand cmd; …
Dan Hermann
  • 1,107
  • 1
  • 13
  • 27
1
2 3
23 24