Skip to content

Compare async/await to ContinueWith #47075

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions docs/csharp/asynchronous-programming/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,36 @@ The code completes the asynchronous breakfast tasks in about 15 minutes. The tot

The final code is asynchronous. It more accurately reflects how a person might cook breakfast. Compare the final code with the first code sample in the article. The core actions are still clear by reading the code. You can read the final code the same way you read the list of instructions for making a breakfast, as shown at the beginning of the article. The language features for the `async` and `await` keywords provide the translation every person makes to follow the written instructions: Start tasks as you can and don't block while waiting for tasks to complete.

## Async/await vs ContinueWith

The `async` and `await` keywords provide syntactic simplification over using <xref:System.Threading.Tasks.Task.ContinueWith%2A?displayProperty=nameWithType> directly. While `async`/`await` and `ContinueWith` have similar semantics for handling asynchronous operations, the compiler doesn't necessarily translate `await` expressions directly into `ContinueWith` method calls. Instead, the compiler generates optimized state machine code that provides the same logical behavior. This transformation provides significant readability and maintainability benefits, especially when chaining multiple asynchronous operations.

Consider a scenario where you need to perform multiple sequential asynchronous operations. Here's how the same logic looks when implemented with `ContinueWith` compared to `async`/`await`:

### Using ContinueWith

With `ContinueWith`, each step in a sequence of asynchronous operations requires nested continuations:

:::code language="csharp" source="snippets/index/ContinueWith-comparison/Program.cs" id="ContinueWithExample":::

### Using async/await

The same sequence of operations using `async`/`await` reads much more naturally:

:::code language="csharp" source="snippets/index/ContinueWith-comparison/Program.cs" id="AsyncAwaitExample":::

### Why async/await is preferred

The `async`/`await` approach offers several advantages:

- **Readability**: The code reads like synchronous code, making it easier to understand the flow of operations.
- **Maintainability**: Adding or removing steps in the sequence requires minimal code changes.
- **Error handling**: Exception handling with `try`/`catch` blocks works naturally, whereas `ContinueWith` requires careful handling of faulted tasks.
- **Debugging**: The call stack and debugger experience is much better with `async`/`await`.
- **Performance**: The compiler optimizations for `async`/`await` are more sophisticated than manual `ContinueWith` chains.

The benefit becomes even more apparent as the number of chained operations increases. While a single continuation might be manageable with `ContinueWith`, sequences of 3-4 or more asynchronous operations quickly become difficult to read and maintain. This pattern, known as "monadic do-notation" in functional programming, allows you to compose multiple asynchronous operations in a sequential, readable manner.

## Next step

> [!div class="nextstepaction"]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
using System;
using System.Threading.Tasks;

namespace ContinueWithComparison
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("=== ContinueWith approach ===");
await MakeBreakfastWithContinueWith();

Console.WriteLine("\n=== async/await approach ===");
await MakeBreakfastWithAsyncAwait();
}

// <ContinueWithExample>
// Using ContinueWith - demonstrates the complexity when chaining operations
static Task MakeBreakfastWithContinueWith()
{
return StartCookingEggsAsync()
.ContinueWith(eggsTask =>
{
var eggs = eggsTask.Result;
Console.WriteLine("Eggs ready, starting bacon...");
return StartCookingBaconAsync();
})
.Unwrap()
.ContinueWith(baconTask =>
{
var bacon = baconTask.Result;
Console.WriteLine("Bacon ready, starting toast...");
return StartToastingBreadAsync();
})
.Unwrap()
.ContinueWith(toastTask =>
{
var toast = toastTask.Result;
Console.WriteLine("Toast ready, applying butter...");
return ApplyButterAsync(toast);
})
.Unwrap()
.ContinueWith(butteredToastTask =>
{
var butteredToast = butteredToastTask.Result;
Console.WriteLine("Butter applied, applying jam...");
return ApplyJamAsync(butteredToast);
})
.Unwrap()
.ContinueWith(finalToastTask =>
{
var finalToast = finalToastTask.Result;
Console.WriteLine("Breakfast completed with ContinueWith!");
});
}
// </ContinueWithExample>

// <AsyncAwaitExample>
// Using async/await - much cleaner and easier to read
static async Task MakeBreakfastWithAsyncAwait()
{
var eggs = await StartCookingEggsAsync();
Console.WriteLine("Eggs ready, starting bacon...");

var bacon = await StartCookingBaconAsync();
Console.WriteLine("Bacon ready, starting toast...");

var toast = await StartToastingBreadAsync();
Console.WriteLine("Toast ready, applying butter...");

var butteredToast = await ApplyButterAsync(toast);
Console.WriteLine("Butter applied, applying jam...");

var finalToast = await ApplyJamAsync(butteredToast);
Console.WriteLine("Breakfast completed with async/await!");
}
// </AsyncAwaitExample>

static async Task<object> StartCookingEggsAsync()
{
Console.WriteLine("Starting to cook eggs...");
await Task.Delay(1000);
return new { Item = "Eggs" };
}

static async Task<object> StartCookingBaconAsync()
{
Console.WriteLine("Starting to cook bacon...");
await Task.Delay(1000);
return new { Item = "Bacon" };
}

static async Task<object> StartToastingBreadAsync()
{
Console.WriteLine("Starting to toast bread...");
await Task.Delay(1000);
return new { Item = "Toast" };
}

static async Task<object> ApplyButterAsync(object toast)
{
Console.WriteLine("Applying butter...");
await Task.Delay(500);
return new { Item = "Buttered Toast" };
}

static async Task<object> ApplyJamAsync(object butteredToast)
{
Console.WriteLine("Applying jam...");
await Task.Delay(500);
return new { Item = "Completed Toast" };
}
}
}
Loading