Home
Search
Task ExamplesUse the Task type and call Task.Run with ContinueWith and Wait. Specify a CancellationToken.
C#
This page was last reviewed on Nov 17, 2022.
Task. This C# 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
Shows a method
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.
Lambda
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).
Shows a method
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::"); } }
::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.
For
Tip When a task is canceled, we must manually return from it (or throw a TaskCancelledException).
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}"); } } }
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.
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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2022 (simplify).
Home
© 2007-2022 sam allen.
see site info on the changelog.