Non Blocking C# Task Cancelling

Standard

In our previous sample snippet, Cancel a Loop in a Task with CancellationTokens in c# , I try to explain how we can get out of a looping c# task, but a problem may arise from that situation. If we were to wait for any result out of that Task, we would be blocking the calling thread until the task returned, which is not good if we are on the main thread. We would locking our UI and might crash our application.

So I’ve been testing different ways to get out of that loop without causing any trouble, and you can achieve what we want many different ways.

So, to begin with, I think I would correctly assume that it is only necessary to wait for a task to complete if that task will return something. If there is no return value, why would we want to call wait on it? We can just break out of it, correct me if I’m wrong. If we have a return value, then it is necessary to surround the wait call on the task with try/catch to receive its result. But then again, we can avoid the locking here with a continuation task, which will create and start the task after the first one completes, giving us the result from the previous task to work with.

Continue reading

Cancel a Loop in a Task with CancellationTokens in C#

Standard

This post explains the use of Cancellation Token in C# using Tasks, which are available since .Net Framework 4.

Say you’ve created a asynchronous Task. The method you’re running inside your task contains a loop ( infinite or not ), and you want to break out of it peacefully. You would need to create a CancellationTokenSource and pass a Cancellation Token to the Task so it can be accessed in the main loop. Continue reading