SHARE:

C#: Make your delegates asynchronous from synchronous delegates

Introduction

I wanted to write this post because I realized that a lot of developers have difficulty writing asynchronous delegates. I often see synchronous delegates in code review that could be transformed. So in this post I will show you how to proceede without however going over the usefulness of asynchronism, this is not the purpose of this post.

Synchronous delegates

There are 4 types of delegates in C #, you have delegates that:

  • Return a result
  • Does not return a result

but also delegates who:

  • Take one or more parameters
  • Does not take any parameters.

So that’s 4 ways to write a delegate, now let’s see what it looks like:

  1. Delegate that doesn’t take any parameter and doesn’t return any value: Action
  2. Delegate that takes one or several parameters and doesn’t return any value: Action<Tin>
  3. Delegate that doesn’t take any parameter and returns a value: Func<Tout>
  4. Delegate that takes one or several parameters and returns a value: Func<Tin, Tout>

Let’s look at a concrete example how this is implemented in practice:

Synchronous to asynchronous delegates

The rule for obtaining a synchronous delegate is simple:
It doesn’t matter if this is an Action or a Func, the asynchronous version will always be a Func returning a Task which gives :

  1. Asynchronous Delegate that doesn’t take any parameter and doesn’t return any value: Func<Task>
  2. Asynchronous Delegate that takes one or several parameter and doesn’t return any value: Func<Tin, Task>
  3. Asynchronous Delegate that doesn’t take any parameter and returns a value: Func<Task<Tout>>
  4. Asynchronous Delegate that takes one or several parameters and returns a value: Func<Tin, Task<Tout>>

Example:

That’s it!

I hope this tutorial helped you to understand how to transform your delegates into asynchronous delegates! Happy programming 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: