Sam
Sam

Reputation: 4339

Async func is not awaiting

I am writing a wrapper function that executes an arbitrary number of async tasks and will provide retry and error handling policy. I'm having an issue awaiting the result of the async tasks.

The method call looks like this:

Execute(async () => await someAsyncFunction(someValue), async () await someOtherFunction(someValue))

My method implementation looks like this:

void Execute<T1, T2>(Func<T1> fn1, Func<T2> fn2, ... /* overloads for up to 6 functions */)
{
    fn1();
    fn2();
    /* ... */
}

I've not yet applied the error handling and retry policy, but from debugging I've noticed that stepping over fn1 or fn2 is immediate, even when I put a large delay in, for example:

async Task someAsyncFunction(object value)
{
    await Task.Delay(10000);
    //...
}

Is it possible to achieve what I want with async methods?

Upvotes: 0

Views: 1561

Answers (1)

John Wu
John Wu

Reputation: 52210

An async "action" is actually a function that returns a Task, so it'll be a Func<Task>. You can create a collection of tasks and then await them all with Task.WhenAll. You can supply a flexible number of arguments using the params keyword.

Note also that Execute() must itself be async in order to make async calls.

public class Program
{
    static async Task Execute(params Func<Task>[] actions)
    {
        var tasks = actions.Select( action => action() );
        await Task.WhenAll(tasks);
    }

    public static async Task MainAsync()
    {
        await Execute
        (
            async () => 
            {
                await Task.Delay(3000);
                Console.WriteLine("Function 1 done");
            }
            ,
            async () =>
            {
                await Task.Delay(3000);
                Console.WriteLine("Function 2 done");
            }
        );
    }

    public static void Main()
    {
        MainAsync().GetAwaiter().GetResult();
    }
}

Output:

Function 2 done
Function 1 done

Example code on DotNetFiddle

Upvotes: 3

Related Questions