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:
- Delegate that doesn’t take any parameter and doesn’t return any value: Action
- Delegate that takes one or several parameters and doesn’t return any value: Action<Tin>
- Delegate that doesn’t take any parameter and returns a value: Func<Tout>
- 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 :
- Asynchronous Delegate that doesn’t take any parameter and doesn’t return any value: Func<Task>
- Asynchronous Delegate that takes one or several parameter and doesn’t return any value: Func<Tin, Task>
- Asynchronous Delegate that doesn’t take any parameter and returns a value: Func<Task<Tout>>
- 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 🙂