.NET by Patrik

Asynchronous programming

The Task asynchronous programming model (TAP) provides an abstraction over asynchronous code. You write code as a sequence of statements, just like always. You can read that code as though each statement completes before the next begins. The compiler performs many transformations because some of those statements may start work and return a Task representing the ongoing work.

...see more

In C#, Task.Delay and Thread.Sleep are both used to introduce delays or pauses in the execution of your code, but they have different use cases and implications.

In summary, use Task.Delay when working with asynchronous code and you want to avoid blocking the current thread. Use Thread.Sleep when you explicitly want to block the current thread, but be cautious about using it in scenarios where responsiveness is important, such as in GUI applications. In modern C# applications, with the widespread use of async/await, Task.Delay is often the more appropriate choice.

Further Resources:

...see more

C#'s async/await pattern simplifies asynchronous programming, but integrating it into console applications poses a challenge. The traditional static void Main() method can't be marked as async, leading to compiler errors when attempting to use await directly.

Workaround Strategies:

  • Separate Async Method: Encapsulate asynchronous operations within a separate method marked as async. Then, invoke this method from Main() using .GetAwaiter().GetResult() to execute it synchronously. This approach ensures exceptions are unwrapped properly, avoiding the AggregateException that occurs with .Result or .Wait().

  • Async Main (C# 7.1 and Later): Starting with C# 7.1, you can define the entry point as static async Task Main(), allowing the use of await directly within Main(). This modernizes the approach and simplifies asynchronous code execution in console applications.

For a detailed explanation and code examples see Async/await in a console application.

Comments