Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel await Task.Delay()?

Tags:

c#

async-await

As you can see in this code:

public async void TaskDelayTest() {      while (LoopCheck)      {           for (int i = 0; i < 100; i++)           {                textBox1.Text = i.ToString();                await Task.Delay(1000);           }      } } 

I want it to set textbox to string value of i with one second period until I set LoopCheck value to false . But what it does is that it creates all iteration ones in for all and even if I set LoopCheck value to false it still does what it does asyncronously.

I want to cancel all awaited Task.Delay() iteration when I set LoopCheck=false. How can I cancel it?

like image 304
Zgrkpnr Avatar asked Apr 04 '14 20:04

Zgrkpnr


People also ask

How do I cancel async tasks?

You can cancel an asynchronous operation after a period of time by using the CancellationTokenSource. CancelAfter method if you don't want to wait for the operation to finish.

What is task delay in C#?

Delay(TimeSpan) Creates a task that completes after a specified time interval. Delay(Int32, CancellationToken) Creates a cancellable task that completes after a specified number of milliseconds.

What is a cancellation token C#?

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.

What happens if you do not await a task?

If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.


1 Answers

Use the overload of Task.Delay which accepts a CancellationToken

public async Task TaskDelayTest(CancellationToken token) {     while (LoopCheck)     {         token.throwIfCancellationRequested();         for (int i = 0; i < 100; i++)         {             textBox1.Text = i.ToString();             await Task.Delay(1000, token);         }     } }  var tokenSource = new CancellationTokenSource(); TaskDelayTest(tokenSource.Token); ... tokenSource.Cancel(); 
like image 135
James Avatar answered Sep 20 '22 07:09

James