diff --git a/docs/csharp/asynchronous-programming/index.md b/docs/csharp/asynchronous-programming/index.md index 4879d49130072..be81a52d2bb17 100644 --- a/docs/csharp/asynchronous-programming/index.md +++ b/docs/csharp/asynchronous-programming/index.md @@ -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 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"] diff --git a/docs/csharp/asynchronous-programming/snippets/index/ContinueWith-comparison/ContinueWith-comparison.csproj b/docs/csharp/asynchronous-programming/snippets/index/ContinueWith-comparison/ContinueWith-comparison.csproj new file mode 100644 index 0000000000000..aee73149c0567 --- /dev/null +++ b/docs/csharp/asynchronous-programming/snippets/index/ContinueWith-comparison/ContinueWith-comparison.csproj @@ -0,0 +1,8 @@ + + + + Exe + net9.0 + + + \ No newline at end of file diff --git a/docs/csharp/asynchronous-programming/snippets/index/ContinueWith-comparison/Program.cs b/docs/csharp/asynchronous-programming/snippets/index/ContinueWith-comparison/Program.cs new file mode 100644 index 0000000000000..2f12ffd4e5d1a --- /dev/null +++ b/docs/csharp/asynchronous-programming/snippets/index/ContinueWith-comparison/Program.cs @@ -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(); + } + + // + // 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!"); + }); + } + // + + // + // 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!"); + } + // + + static async Task StartCookingEggsAsync() + { + Console.WriteLine("Starting to cook eggs..."); + await Task.Delay(1000); + return new { Item = "Eggs" }; + } + + static async Task StartCookingBaconAsync() + { + Console.WriteLine("Starting to cook bacon..."); + await Task.Delay(1000); + return new { Item = "Bacon" }; + } + + static async Task StartToastingBreadAsync() + { + Console.WriteLine("Starting to toast bread..."); + await Task.Delay(1000); + return new { Item = "Toast" }; + } + + static async Task ApplyButterAsync(object toast) + { + Console.WriteLine("Applying butter..."); + await Task.Delay(500); + return new { Item = "Buttered Toast" }; + } + + static async Task ApplyJamAsync(object butteredToast) + { + Console.WriteLine("Applying jam..."); + await Task.Delay(500); + return new { Item = "Completed Toast" }; + } + } +} \ No newline at end of file