how can allow this loop to call async methods

Viewed 41

I have this loop:

public static void ForEachValue<T>(Action<T> F)
{
    foreach (var E in GetValues<T>())
    {
        F(E);
    }
}

It allows to iterate through enum members and call a method for each.

I would like to allow to take async methods as well and await them, but I can't find the syntax that would work.

1 Answers

An async method should be returning a Task so you need to use Func<T, Task> instead of Action<T>. So you could do this and await every task:

public static async Task ForEachValue<T>(Func<T, Task> F)
{
    foreach (var E in GetValues<T>())
    {
        await F(E);
    }
}

Or you could even shorten it to this:

public static async Task ForEachValue<T>(Func<T, Task> F)
{
    var tasks = GetValues<T>().Select(F);
    await Task.WhenAll(tasks);  
}
Related