Now, using the chaining method, we are going to use the async
and await
keywords in functional programming. Suppose we have three tasks, as shown in the following code snippet, and we need to chain them together:
public async static Task<int> FunctionA( int a) => await Task.FromResult(a * 1); public async static Task<int> FunctionB( int b) => await Task.FromResult(b * 2); public async static Task<int> FunctionC( int c) => await Task.FromResult(c * 3);
For that purpose, we have to create a new extension method for Task<T>
named MapAsync
, with the following implementation:
public static class ExtensionMethod { public static async Task<TResult> MapAsync<TSource, TResult>( this Task<TSource> @this, Func<TSource, Task<TResult>> fn) => await fn(await @this); }
The MapAsync()
method allows us to define the method as async
, accept the task returned from the async
method, and await
the call to the delegate. The following is the complete code we use to chain the three tasks that we can find in the AsyncChain.csproj
project:
public partial class Program { public async static Task<int> FunctionA( int a) => await Task.FromResult(a * 1); public async static Task<int> FunctionB( int b) => await Task.FromResult(b * 2); public async static Task<int> FunctionC( int c) => await Task.FromResult(c * 3); public async static void AsyncChain() { int i = await FunctionC(10) .MapAsync(FunctionB) .MapAsync(FunctionA); Console.WriteLine("The result = {0}", i); } }
If we run the preceding AsyncChain()
method, we will get the following output on the console: