I am using SignalR. The function on the Hub often return a Task. I now have a function that will add a connection to a bunch of groups. I would like to return a Task that represents all of these Tasks.
I found a perfect function for that: Task.WhenAll. However this is a new function in .NET 4.5 and I am still stuck on .NET 4.
Hence I decided to write my own version of it until we can move to .NET 4.5. Because there are often some caveats when it comes to multithreading (e.g. thread pool stuff), I am not sure if my implementation is correct:
public static Task WhenAll(IEnumerable<Task> tasks)
{
return Task.Factory.StartNew(() => Task.WaitAll(tasks.ToArray()));
}
Functionally, it works I think, but don't I get an extra blocked thread for the new Task? Or is this unavoidable?
Edit: Here is how I would use it with SignalR:
public static Task Add(this IGroupManager groupManager, string connectionId,
IEnumerable<string> groups)
{
return WhenAll(groups.Select(group => groupManager.Add(connectionId, group)));
}