C# – Async/await with a Func delegate

To make a Func delegate awaitable, you have to make its out parameter a Task, like this: This Func accepts an int parameter and returns a Task. Since it returns a Task, it can be awaited. Notice that this isn’t returning a value. Normally you’d use an Action delegate if you didn’t want to return … Read more

C# – Handle a faulted Task’s exception

When a Task throws an exception and stops running, it has faulted. The question is, how do you get the exception that was thrown from the faulted Task? This depends on if you’re awaiting the Task or not. This article shows how to handle a faulted Task’s exception in two scenarios: when you’re awaiting the … Read more

C# – Using Channel as an async queue

The Channel class (from System.Threading.Channels) is a non-blocking async queue. It implements the producer-consumer pattern, which has two parts: Compare this with using BlockingCollection, which is a blocking concurrent queue. In this article, I’ll show how to use a Channel. 1 – Create the Channel The first step is to create the Channel object. Here’s … Read more

C# – Async Main

The Async Main feature was added in C# 7.1 and works with all overloads of the Main() method. To make the Main() method async, add async Task to the method signature, like this: This is syntax sugar that compiles down to calling GetAwaiter().GetResult() on whatever you’re awaiting. In other words, it’s equivalent to doing the … Read more

C# – Fixing the Sync over Async antipattern

The Sync over Async antipattern is when you’re using a blocking wait on an async method, instead of awaiting the results asynchronously. This wastes the thread, causes unresponsiveness (if called from the UI), and exposes you to potential deadlocks. There are two causes: In this article I’ll show an example of the Sync over Async … Read more

How to set a timeout for TcpClient.ConnectAsync()

TcpClient has no direct way to set the connection timeout. It doesn’t have any parameters that allow you to control it, and SendTimeout / ReceiveTimeout don’t apply to the initial connection. The way I control the connection timeout is by awaiting a Task.WhenAny() with TcpClient.ConnectAsync() and Task.Delay(). Task.WhenAny() returns when any of the tasks complete. … Read more