C# Task Examples (Task.Run, ContinueWith and Wait)

Use the Task type and call Task.Run with ContinueWith and Wait. Specify a CancellationToken.
Task. This type is used to schedule a method on the thread pool. We can use Task.Run to call a method at some point in the future, and ContinueWith to add another method after that.async
With Wait, meanwhile, we can wait for all the methods in our queue to be called. In this way we can chain methods, one after another, on a thread pool.
An example. Consider this example program. It includes the System.Threading.Tasks namespace. And we invoke Task.Run in Main() when it begins.

Task.Run: We pass a lambda expression to Task.Run that calls the useful Method1() method.


ContinueWith: Here we pass another lambda expression, one that receives a Task argument "task" and calls Method2().

Wait: We wait for all the methods to complete—this allows all the console messages to appear before the program exits.

Tip: With Task.Run and ContinueWith, we impose order on the methods that are added to the method queue (for the thread pool).

C# program that uses Task.Run, ContinueWith using System; using System.Threading.Tasks; class Program { static void Main() { // Call Task.Run and invoke Method1. // ... Then call Method2. // Finally wait for Method2 to finish for terminating the program. Task.Run(() => Method1()).ContinueWith(task => Method2()).Wait(); } static void Method1() { Console.WriteLine("::Method1::"); } static void Method2() { Console.WriteLine("::Method2::"); } } Output ::Method1:: ::Method2::
CancellationToken. Suppose we have a long-running task, and we may want to cancel it at some point (end it before it completes). We can use a CancellationTokenSource and CancellationToken.

Main: We first create a CancellationTokenSource. We access the Token from it (this is a CancellationToken).

Task.Run: We create a Task and run it, specifying the cancellation token as the second argument. We also pass the token to DoSomething().

DoSomething: This method receives a CancellationToken and on each iteration of its loop, it tests for IsCancellationRequested.

Tip: When a task is canceled, we must manually return from it (or throw a TaskCancelledException).

C# program that uses CancellationToken using System; using System.Threading; using System.Threading.Tasks; class Program { static void Main() { // Create CancellationTokenSource. var source = new CancellationTokenSource(); // ... Get Token from source. var token = source.Token; // Run the DoSomething method and pass it the CancellationToken. // ... Specify the CancellationToken in Task.Run. var task = Task.Run(() => DoSomething(token), token); // Wait a few moments. Thread.Sleep(500); // Cancel the task. // ... This affects the CancellationTokens in the source. Console.WriteLine("Main::Cancel"); source.Cancel(); // Wait more. Thread.Sleep(500); } static void DoSomething(CancellationToken token) { // Do something important. for (int i = 0; i < 100; i++) { // Wait a few moments. Thread.Sleep(100); // See if we are canceled from our CancellationTokenSource. if (token.IsCancellationRequested) { Console.WriteLine("Method1 canceled"); return; } Console.WriteLine($"Method1 running... {i}"); } } } Output Method1 running... 0 Method1 running... 1 Method1 running... 2 Method1 running... 3 Main::Cancel Method1 canceled
Notes, cancellation. We can call Cancel() on the CancellationTokenSource from any method—even if the method being run as a task. In the above example, we call Cancel() in Main.

But: An example on Microsoft Docs calls Cancel in the target method. I recommend reviewing the Microsoft example too.

CancellationToken: Microsoft Docs
Windows programs. Suppose we have a method we want to call, and we want to use its result in a control in a Windows Forms or WPF program.

ContinueWith: We can call a method with ContinueWith that uses thread-safe logic (InvokeRequired, BeginInvoke) if needed.

So: The final step in a chain of methods started by Task.Run sets a property on a Windows program control.

Note: Thanks to Paul Bright for the idea of using ContinueWith to set a UI control value.

A summary. With Task, and its static method Task.Run, we can start a Task. ContinueWith allows us to build a sequence of methods—which we can wait to terminate with the Wait() method.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls