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?
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.
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.
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With