π Lecture 33 β Long Running Operations and Threading
π Overview: This lecture addresses the problem of UI unresponsiveness caused by long-running operations, which block the main UI thread. It introduces worker threads, thread marshaling via Dispatcher and SynchronizationContext, thread pools, and the Task-based asynchronous pattern including continuations and TaskCompletionSource.
ποΈ Topics Covered
The lecture covers UI thread marshaling using Dispatcher.BeginInvoke and Invoke, SynchronizationContext for generalized marshaling, ThreadPool for efficient thread reuse, Tasks as a higher-level abstraction over threads with return values and exception handling, continuations for chaining operations, and TaskCompletionSource for creating tasks that are manually driven.
π Lecture Summary
Long Running Operations and UI Responsiveness
Long running operations make applications unresponsive because the main thread is used for rendering the UI and responding to events. The solution is to start a worker thread and update the UI when finished. However, UI updation is usually possible only on the UI thread, so requests must be forwarded (marshaled) to the UI thread.
π Definition β Thread Marshaling: The process of forwarding a request from a worker thread to the UI thread so that UI elements can be safely updated.
The low-level way to marshal is to call BeginInvoke or Invoke on the element's Dispatcher object. Invoke takes a delegate, queues it on the UI thread, but blocks until completion, allowing return values. BeginInvoke does the same without blocking, making it better when no return value is needed.
π Example: Using Dispatcher.BeginInvoke
Partial class mywindow : Window
{
Public mywindow()
{
Initializecomponent();
New Thread(Work).Start();
}
Void Work()
{
Thread.Sleep(5000);
Updatemessage("The answer");
}
Void updatemessage(string message)
{
Action action = () => txtmessage.Text = message;
Dispatcher.begininvoke(action);
}
}
SynchronizationContext
SynchronizationContext can be used for generalized thread marshaling, providing a more portable abstraction.
π Example: Using SynchronizationContext
Partial class mywindow : Window
{
Synchronizationcontext _uisynccontext;
Public mywindow()
{
Initializecomponent();
_uisynccontext = synchronizationcontext.Current;
New Thread(Work).Start();
}
Void Work()
{
Thread.Sleep(5000);
Updatemessage("The answer");
}
Void updatemessage(string message)
{
_uisynccontext.Post(_ => txtmessage.Text = message);
}
}
ThreadPool
The ThreadPool saves the time of thread creation. ThreadPool threads cannot be named and are difficult to debug. They are always background threads. Blocking can degrade performance. The Thread.CurrentThread.IsThreadPoolThread property checks if a thread is from the pool. ThreadPool creates or reduces real threads using a hill climbing algorithm to maximize CPU usage and reduce context switching.
π Example: Using ThreadPool
Threadpool.queueuserworkitem (notused => Console.writeline ("Hello"));
Task.Run (() => Console.writeline ("Hello from the thread pool"));
Tasks
There is no easy way to get a return value from a thread; you can join and use shared data. Exceptions are also difficult to handle. You cannot tell a thread to start something else when finished. Tasks provide a higher-level abstraction. Tasks can be chained using continuations, can use the ThreadPool, and with TaskCompletionSource enable a callback approach.
Starting a task is like creating a thread, except tasks are started right away (hot) and run in a thread pool. Task.Wait() is like Join. The generic subclass Task<TResult> allows returning values, and Task.Result blocks until the result is available.
π Example: Starting and waiting on a Task
Task.Run (() => Console.writeline ("Foo"));
New Thread (() => Console.writeline ("Foo")).Start();
Task task = Task.Run (() =>
{
Thread.Sleep (2000);
Console.writeline ("Foo");
});
Console.writeline (task.iscompleted);
Task.Wait();
π Example: Task with return value
Task<int> task = Task.Run(() => { Console.writeline("Foo"); return 3; });
// ...
Int result = task.Result;
Console.writeline (result);
Tasks propagate exceptions to whoever calls Wait() or accesses Result. Exceptions are wrapped in an AggregateException.
π Example: Task exception handling
Task task = Task.Run (() => { throw null; });
Try
{
Task.Wait();
}
Catch (aggregateexception aex)
{
If (aex.innerexception is nullreferenceexception)
Console.writeline ("Null!");
Else
Throw;
}
Continuations
Continuations allow you to specify what happens when a task finishes. There are two ways to attach continuations.
π Formula: task.continuewith(antecedent => { ... }) β Runs the delegate when the antecedent task completes.
π Formula: var awaiter = task.getawaiter(); awaiter.oncompleted(() => { ... }) β Another way to attach a continuation using the awaiter pattern.
π Example: Continuation using ContinueWith
Task<int> primenumbertask = Task.Run (() =>
Enumerable.Range (2, 3000000).Count (n =>
Enumerable.Range (2, (int)Math.Sqrt(n)-1).All (i => n % i > 0)));
Primenumbertask.continuewith (antecedent =>
{
Int result = antecedent.Result;
Console.writeline (result);
});
π Example: Continuation using awaiter
Var awaiter = primenumbertask.getawaiter();
Awaiter.oncompleted(() =>
{
Int result = awaiter.getresult();
Console.writeline (result);
});
If a synchronization context is present, the continuation runs on the UI thread.
TaskCompletionSource
TaskCompletionSource represents any operation that starts and finishes some time later. It creates a "slave" task that you manually drive and mark as finished. It is ideal for I/O-bound work. It provides all benefits of tasks (returns, exceptions, continuations) without blocking a thread. Create a task which you can wait on and attach continuations, controlled by these operations:
π Definition β TaskCompletionSource<TResult>: A class that enables creation of a Task<TResult> that can be manually signaled as completed, faulted, or canceled.
π Formula: tcs.SetResult(result), tcs.SetException(exception), tcs.SetCanceled() β Methods that signal the task. Call exactly once.
π‘ Why this matters: TaskCompletionSource allows you to create tasks for I/O-bound or timer-based operations without dedicating a thread, improving scalability.
π Example: Basic TaskCompletionSource with thread
Var tcs = new taskcompletionsource<int>();
New Thread (() => {
Thread.Sleep (5000); tcs.setresult (42);
}).Start();
Task<int> task = tcs.Task;
Console.writeline (task.Result) // prints 42 after 5s
π Example: Creating a custom Run method with TaskCompletionSource
Task<tresult> Run<tresult> (Func<tresult> function)
{
Var tcs = new taskcompletionsource <tresult>();
New Thread (() =>
{
Try { tcs.setresult (function()); }
Catch (Exception ex) { tcs.setexception (ex);}
}).Start();
Return tcs.Task;
}
// Usage
Task<int> task = Run (() => { Thread.Sleep (5000); return 42; });
π Example: Timer-based TaskCompletionSource (no blocking thread)
Task<int> getanswertolife()
{
Var tcs = new taskcompletionsource<int>();
Var timer = new System.Timers.Timer(5000) { autoreset = false };
Timer.Elapsed += delegate { timer.Dispose(); tcs.setresult(42); };
Timer.Start();
Return tcs.Task;
}
// Using with continuation
Var awaiter = getanswertolife().getawaiter();
Awaiter.oncompleted (() => Console.writeline (awaiter.getresult()));
π Example: Implementing Task.Delay with TaskCompletionSource
Task Delay(int milliseconds)
{
Var tcs = new taskcompletionsource<object>();
Var timer = new System.Timers.Timer(milliseconds) { autoreset = false };
Timer.Elapsed += delegate { timer.Dispose(); tcs.setresult(null); };
Timer.Start();
Return tcs.Task;
}
// Equivalent to Task.Delay
Delay(5000).getawaiter().oncompleted (() => Console.writeline (42));
Delay(5000).continuewith (ant => Console.writeline (42));
Task.Delay(5000).getawaiter().oncompleted (() => Console.writeline (42));
Task.Delay(5000).continuewith (ant => Console.writeline (42));
β Key Takeaways
For the exam, remember that UI updates must occur on the UI thread using Dispatcher.BeginInvoke/Invoke or SynchronizationContext.Post. Tasks are a higher-level abstraction than threads, providing return values via Task.Result, exception handling via AggregateException, and continuations via ContinueWith or awaiter.OnCompleted. TaskCompletionSource enables creating manually-driven tasks ideal for I/O-bound operations without blocking a thread. Task.Delay is a non-blocking alternative to Thread.Sleep that works with continuations.
π§ Quick Revision Questions
- What is the difference between Dispatcher.Invoke and Dispatcher.BeginInvoke in terms of blocking behavior?
- How does SynchronizationContext help with thread marshaling in a portable way?
- What problem does the Task class solve compared to raw threads?
- How are exceptions propagated in Tasks, and what wrapper exception type is used?
- What is TaskCompletionSource and why is it ideal for I/O-bound operations?
π Lecture 34 β Async and Await in C#
π Overview: This lecture continues the discussion on asynchronous programming in C#, focusing on the
asyncandawaitkeywords introduced in C# 5.0. It explains how these keywords simplify writing asynchronous code by eliminating the complex plumbing required with tasks, continuations, and state machines, and demonstrates their application in both console and UI applications.
ποΈ Topics Covered
The lecture covers making CPU-bound tasks asynchronous using Task.Run, the complexity of manual continuation-based async patterns, the introduction of C# 5.0's async and await keywords to simplify async code, the expansion of await into continuations by the compiler, capturing local state in async methods, and applying async patterns to UI applications to maintain responsiveness. It also includes examples of downloading web pages asynchronously and understanding the UI message loop's role in continuations.
π Lecture Summary
Creating CPU-Bound Async Tasks with Task.Run
The lecture begins with synchronous code that counts primes across ten million-number ranges. The synchronous GetPrimesCount method uses ParallelEnumerable.Range within Count to find primes between intervals. The DisplayPrimeCounts method loops through ten intervals, calling GetPrimesCount and printing results sequentially. The output shows prime counts for each million-number range from 0β999999 up to 9000000β9999999, ending with "Done!".
To make this asynchronous in a coarse-grained way, we wrap the entire synchronous DisplayPrimeCounts call in Task.Run. A more granular approach creates an async method GetPrimesCountAsync that returns Task<int>. This method runs the prime counting computation on a thread pool thread using Task.Run. When calling it, we get the awaiter from the returned task, then attach a continuation using Awaiter.OnCompleted to print the result when the task completes. However, this approach falls back to sequential behavior: the continuation calls the next iteration inside itself, leading to complex recursive structure.
Task<int> GetPrimesCountAsync(int start, int count)
{
return Task.Run(() =>
ParallelEnumerable.Range(start, count).Count(n =>
Enumerable.Range(2, (int)Math.Sqrt(n) - 1).All(i => n % i > 0)));
}
π Definition β Awaiter: An object obtained from a task (via GetAwaiter()) that provides OnCompleted for attaching continuations and GetResult() to retrieve the task's result or propagate exceptions.
π Pattern: var awaiter = task.GetAwaiter(); awaiter.OnCompleted(() => { /* continuation */ }); β Attaches code to run after the task completes without blocking the calling thread.
Manual Async State Machine Pattern
To make DisplayPrimeCounts itself async while keeping sequential output, a manual state machine approach is needed. A method DisplayPrimeCountsFrom takes an index i, awaits the prime count for that interval, and in the continuation prints the result and either recursively calls itself with i+1 (if more intervals remain) or prints "Done". This pattern becomes verbose and error-prone.
To encapsulate this, the lecture introduces a PrimesStateMachine class using a TaskCompletionSource<object>. The class exposes a public Task property. The DisplayPrimeCountsFrom method follows the same recursive continuation pattern, but when all intervals are processed (i >= 10), it calls _tcs.SetResult(null) to signal completion. This manual approach is complex and difficult to maintain.
class PrimesStateMachine
{
TaskCompletionSource<object> _tcs = new TaskCompletionSource<object>();
public Task Task { get { return _tcs.Task; } }
public void DisplayPrimeCountsFrom(int i)
{
var awaiter = GetPrimesCountAsync(i * 1000000 + 2, 1000000).GetAwaiter();
awaiter.OnCompleted(() =>
{
Console.WriteLine(awaiter.GetResult());
if (++i < 10) DisplayPrimeCountsFrom(i);
else { Console.WriteLine("Done"); _tcs.SetResult(null); }
});
}
}
π Definition β TaskCompletionSource<T>: A class that lets you create a Task<T> and manually control its completion by calling SetResult, SetException, or SetCanceled. It's used when implementing custom async patterns or state machines.
π‘ Why this matters: Manual state machines are tedious to write correctly. C# 5.0's async/await automates this entire pattern, generating the state machine code automatically.
C# 5.0 Async and Await Keywords
C# 5.0 introduces the async and await keywords, which eliminate all the manual plumbing for asynchronous code. The await keyword simplifies attaching continuations, handling synchronous completion (when the task is already completed), and other details. The compiler automatically transforms await expressions into the equivalent awaiter-and-continuation code.
The expansion of await works as follows:
var result = await expression;
statement(s);
Expands to:
var awaiter = expression.GetAwaiter();
awaiter.OnCompleted(() =>
{
var result = awaiter.GetResult();
statement(s);
});
The async keyword can be applied to methods returning void, Task, or Task<TResult>. When a method is marked async and hits an await, control returns to the caller (the method is non-blocking). A continuation is attached to the awaited task. When the task completes, execution resumes: if an exception occurred, it's rethrown; otherwise the return value is assigned to the await expression.
async Task DisplayPrimeCounts()
{
for (int i = 0; i < 10; i++)
Console.WriteLine(await GetPrimesCountAsync(i * 1000000 + 2, 1000000) +
" primes between " + (i * 1000000) + " and " + ((i + 1) * 1000000 - 1));
Console.WriteLine("Done!");
}
π Definition β async keyword: A modifier applied to method declarations that tells the compiler to treat await as a special keyword, transforming the method into a state machine that can suspend and resume execution.
π Definition β await keyword: An operator that asynchronously waits for a task to complete. It suspends the execution of the current method until the awaited task finishes, returning control to the caller in the meantime. After the task completes, execution resumes from where it left off.
Capturing Local State with Await
A key power of await is its ability to capture local state. When execution resumes in the continuation after an await, local variables retain their values from before the await. The compiler translates async methods into state machines that automatically preserve this state across suspension points. If there's a sync context (e.g., on a UI thread), the continuation runs on the same thread; otherwise it runs on any available thread pool thread.
π‘ Why this matters: Without async/await, preserving local state across asynchronous operations requires complex manual state management (like the PrimesStateMachine class). The compiler handles this automatically, making async code as simple as synchronous code.
Async in UI Applications
The lecture demonstrates applying async/await to a WPF UI application to keep it responsive during CPU-bound work. The synchronous version has a Go() method that iterates through ranges, calls the synchronous GetPrimesCount, and updates the _results TextBlock. This blocks the UI thread, making the application unresponsive.
The asynchronous version uses GetPrimesCountAsync (which runs the computation on a thread pool via Task.Run) and await in the Go() method. The Go() method is marked async void (appropriate for event handlers). Before the loop, the Go button is disabled (_button.IsEnabled = false). Inside the loop, each await releases the UI thread, allowing it to process other events. After the loop completes, the button is re-enabled. This simple change keeps the UI responsive while the prime calculations run in parallel.
async void Go()
{
_button.IsEnabled = false;
for (int i = 1; i < 5; i++)
_results.Text += await GetPrimesCountAsync(i * 1000000, 1000000) +
" primes between " + (i * 1000000) + " and " + ((i + 1) * 1000000 - 1) +
Environment.NewLine;
_button.IsEnabled = true;
}
An I/O-bound example downloads web pages asynchronously using WebClient.DownloadDataTaskAsync, which returns Task<byte[]>. The Go() method iterates through URLs, awaits each download, updates the results TextBlock with page lengths, catches any WebException, and ensures the button is re-enabled in a finally block. Despite the async nature, exception handling and finalization work exactly as they would in synchronous code.
async void Go()
{
_button.IsEnabled = false;
string[] urls = "www.albahari.com www.oreilly.com www.linqpad.net".Split();
int totalLength = 0;
try
{
foreach (string url in urls)
{
var uri = new Uri("http://" + url);
byte[] data = await new WebClient().DownloadDataTaskAsync(uri);
_results.Text += "Length of " + url + " is " + data.Length + Environment.NewLine;
totalLength += data.Length;
}
_results.Text += "Total length: " + totalLength;
}
catch (WebException ex)
{
_results.Text += "Error: " + ex.Message;
}
finally { _button.IsEnabled = true; }
}
Understanding the UI Message Loop
The lecture explains what happens "underneath" the UI message loop. The UI thread runs a message loop: while (!ThisApplication.Ended) { /* wait for message; dispatch */ }. When an event handler (like click) fires, Go() runs until it hits await, at which point control returns to the message loop. The compiler's expansion of await ensures a continuation is set up. Because the await occurs on a UI thread, the continuation is posted on the sync context, which ensures it runs via the message loop. This means Go() runs pseudo-concurrently with the UI thread β true concurrency happens only while DownloadDataTaskAsync (or similar async operations) are executing on background threads.
The alternative coarse-grained approach uses Task.Run(() => Go()) to run the entire loop on a thread pool thread, with Dispatcher.BeginInvoke to marshal UI updates back to the UI thread. This is more complex and difficult when progress reporting is needed.
_button.Click += (sender, args) =>
{
_button.IsEnabled = false;
Task.Run(() => Go());
};
void Go()
{
for (int i = 1; i < 5; i++)
{
int result = GetPrimesCount(i * 1000000, 1000000);
Dispatcher.BeginInvoke(new Action(() =>
_results.Text += result + " primes between " + (i * 1000000) +
" and " + ((i + 1) * 1000000 - 1) + Environment.NewLine));
}
Dispatcher.BeginInvoke(new Action(() => _button.IsEnabled = true));
}
π Definition β Synchronization Context (Sync Context): An abstraction that represents a "context" for executing code, typically associated with a specific thread (like the UI thread). The awaiter captures the sync context at the point of await and posts the continuation to it, ensuring UI updates happen on the correct thread.
β Key Takeaways
The critical points to remember from this lecture are: C# 5.0's async and await keywords dramatically simplify asynchronous programming by letting you write code that looks synchronous but behaves asynchronously β the compiler automatically generates the state machine that handles continuations, exception propagation, and local state preservation. await releases the calling thread while the awaited operation runs, then resumes execution on the captured sync context (typically the UI thread for UI applications). For CPU-bound work, use Task.Run inside an async method to offload computation to the thread pool, then await the result. For I/O-bound work, use built-in async methods like WebClient.DownloadDataTaskAsync. Mark event handlers with async void (not async Task) since they must return void, but all other async methods should return Task or Task<T>. The compiler's expansion of await mirrors the manual awaiter/continuation pattern but handles all edge cases automatically, making async code as maintainable as synchronous code.
π§ Quick Revision Questions
-
What is the meaning of the
awaitkeyword in C# 5.0, and what does the compiler expand it into? -
Why must event handlers in UI applications be marked
async voidrather thanasync Task? -
What is the role of the synchronization context in async/await for UI applications?
-
How does the
TaskCompletionSource<T>class relate to the state machine generated by the compiler for async methods? -
In the manual async pattern using continuations, why does the
DisplayPrimeCountsFrommethod call itself recursively inside theOnCompletedcallback, and how doesasync/awaiteliminate this complexity?
π Lecture 35 β Async Programming Patterns and Task Combinators
π Overview: This lecture covers advanced async programming patterns in C#, including returning Task from async methods, parallel execution of async operations, cancellation patterns, progress reporting, and the Task-based Async Pattern (TAP). It explains how the compiler transforms async methods internally using TaskCompletionSource and demonstrates the equivalence between async and synchronous code structures.
ποΈ Topics Covered
The lecture covers returning Task from async void functions, the internal implementation using TaskCompletionSource, comparing async and synchronous code structures, parallel execution with Task.WhenAny, async lambda expressions, cancellation using CancellationToken, progress reporting with IProgress<T>, Task-based Async Pattern (TAP) methods, and task combinators for handling multiple async operations.
π Lecture Summary
Async Method Return Types and Internal Implementation
Async void methods can return Task without explicitly returning it, enabling async call chains. The compiler internally uses TaskCompletionSource to implement methods returning Tasks. When returning Task<TResult>, the internal TCS is signaled with the result value. The compiler transforms the async method into a state machine that creates a TaskCompletionSource, wires up continuations on await points, and returns the TCS.Task to the caller.
π Definition β TaskCompletionSource (TCS): A type that creates a Task which can be manually controlled by calling SetResult, SetException, or SetCanceled methods.
π Formula: Task<TResult> async method β internally creates TCS, signals with tcs.SetResult(value) on completion
π Example: The compiler transforms async Task printanswertolife() into code that creates a TaskCompletionSource<object>, calls Task.Delay(5000).GetAwaiter().OnCompleted() to set a continuation, and in that continuation calls tcs.SetResult(null) after computing the answer.
Async vs Synchronous Code Comparison
The lecture demonstrates that async/await preserves the same programming model as synchronous code. The three steps are: write synchronous code, add async and await keywords, and change return types to Task and Task<TResult> so methods become awaitable. This means developers only need Task.Run for CPU-bound parallel tasks and TaskCompletionSource for I/O-bound operations; the compiler handles the rest.
π‘ Why this matters: This intentional design makes async code as easy to write and reason about as synchronous code, while maintaining non-blocking behavior.
π Example: The async call chain shows:
async Task Go()
{
await printanswertolife();
Console.WriteLine("Done");
}
async Task printanswertolife()
{
int answer = await getanswertolife();
Console.WriteLine(answer);
}
async Task<int> getanswertolife()
{
await Task.Delay(5000);
return 21 * 2;
}
This mirrors the synchronous version where each method calls the next directly, but with non-blocking await.
Parallelism with Async
To run two async tasks in parallel, don't await each immediately. Store the tasks in variables, then await both. This provides true concurrency at the bottom-level operations, though if there's a synchronization context, only pseudo-concurrency is achieved (switching only on await). This means you can increment a shared variable without locking, but you can't assume the same value before and after await.
π Definition β Pseudo-concurrency: When async operations on a UI thread only yield control at await points, running continuations on the same thread rather than truly parallel threads.
π Example:
var task1 = printanswertolife();
var task2 = printanswertolife();
await task1;
await task2;
Both tasks start executing immediately, and the code awaits them both later.
Async Lambda Expressions
Async lambdas can be created for event handlers, delegates, and inline methods. Event handlers must return void, so they use async void. For other scenarios, async lambdas can return Task or Task<TResult>.
π Definition β Async lambda: An anonymous function that uses the async modifier, enabling await inside the lambda body.
π Example: Button click handler with async lambda:
myButton.Click += async(sender, args) =>
{
await Task.Delay(1000);
myButton.Content = "Done";
};
This is equivalent to: async void buttonHandler(object sender, EventArgs args)
Cancellation
Cancellation is implemented using CancellationTokenSource and CancellationToken. Most async methods have built-in cancellation support. The CancellationToken is polled by calling ThrowIfCancellationRequested() which throws OperationCanceledException if cancellation was requested. Many async methods accept CancellationToken directly, like Task.Delay(1000, cancellationToken).
π Definition β CancellationToken: A struct that propagates notification that operations should be canceled. It has an IsCancellationRequested property and ThrowIfCancellationRequested() method.
π Example: Creating cancellation with timeout:
var cancelSource = new CancellationTokenSource(5000);
try { await Foo(cancelSource.Token); }
catch (OperationCanceledException ex)
{ Console.WriteLine("Cancelled"); }
This automatically cancels the operation after 5 seconds.
Progress Reporting
Progress reporting is implemented using the IProgress<T> interface and Progress<T> class. The Progress<T> class captures the SynchronizationContext at creation time, ensuring that progress callbacks run on the correct thread (e.g., UI thread). The IProgress<T> interface has a single method Report(T value).
π‘ Why this matters: Progress<T> solves thread safety issues by marshaling progress reports back to the original synchronization context, making UI updates safe.
π Definition β IProgress<T>: An interface with a Report(T value) method that enables progress reporting from async operations.
π Example:
var progress = new Progress<int>(i => Console.WriteLine(i + " %"));
await Foo(progress);
async Task Foo(IProgress<int> onProgressPercentChanged)
{
await Task.Run(() =>
{
for (int i = 0; i < 1000; i++)
{
if (i % 10 == 0)
onProgressPercentChanged.Report(i / 10);
}
});
}
Task-based Async Pattern (TAP)
TAP defines the standard pattern for async methods in .NET. A TAP method: returns a "hot" (already started) Task or Task<TResult>, has an "Async" suffix (except for combinators), accepts CancellationToken and/or IProgress<T> if supporting cancellation/progress, returns quickly with minimal synchronous phase, and doesn't tie up a thread if I/O-bound.
π Example: TAP method signature: public Task<string> DownloadStringAsync(Uri address, CancellationToken cancellationToken, IProgress<int> progress)
Task Combinators
Task combinators enable working with multiple tasks. Task.WhenAny returns the first task to complete from a collection of tasks. Task.WhenAll waits for all tasks to complete. WhenAny is useful for timeouts and race conditions.
π Definition β Task.WhenAny: A combinator that returns a Task that completes when any of the supplied tasks complete.
π Example: Using WhenAny for timeout:
Task<string> task = someAsyncFunc();
Task winner = await Task.WhenAny(task, Task.Delay(5000));
if (winner != task) throw new TimeoutException();
string result = await task;
β Key Takeaways
Async methods can return Task or Task<TResult> which the compiler implements using TaskCompletionSource, enabling async call chains. The async/await pattern intentionally mirrors synchronous code structure, making it easy to convert between the two styles. For parallelism, start multiple tasks without awaiting until all are collected, enabling true concurrent execution of I/O operations. Cancellation uses CancellationTokenSource/CancellationToken with ThrowIfCancellationRequested(), and many built-in methods accept cancellation tokens directly. The Task-based Async Pattern (TAP) standardizes async methods with "Async" suffix, hot task return, and optional cancellation/progress support, while Task combinators like WhenAny enable sophisticated patterns like timeouts and race conditions.
π§ Quick Revision Questions
- How does the compiler internally implement an async method that returns Task<T>?
- What is the difference between pseudo-concurrency and true concurrency in async operations?
- How do you properly run two async tasks in parallel and wait for both to complete?
- What is the purpose of the Progress<T> class and how does it handle thread marshaling?
- How can you implement a timeout for an async operation using Task.WhenAny and Task.Delay?