3

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.

2
  • 5
    An async method should be returning a Task so you need Func<T, Task> Commented Jul 2, 2019 at 11:27
  • ahh yes; it works; thanks! Commented Jul 2, 2019 at 11:30

1 Answer 1

2

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); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.