Given the following array Func<int>[] funcs and using TPL (Task Parallel Library .NET) how can I evaluate the first result returned by the invocation of any of the functions in funcs.
The main constraint here is to run all of the methods in parallel and stop when the first is returned.
The method definition is something like this:
public static int EvalFirstResult(Func<int>[] funcs);
So, first we need to turn each function into a
Task. That’s done withSelectandTask.Run. Then, once we have that, we can just useTask.WaitAnyto get the result of the first task to finish.Note that the remaining tasks will still finish; we’re not stopping them, we’re just ignoring their results.