Thomas
Thomas

Reputation: 12107

how can allow this loop to call async methods

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.

Upvotes: 3

Views: 52

Answers (1)

DavidG
DavidG

Reputation: 118957

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);  
}

Upvotes: 2

Related Questions