Is this the correct version of .NET 4 for .NET 4.5 WhenAll?

I am using SignalR. A function on a hub often returns a task. Now I have a function that will add a connection to a group of groups. I would like to return a task that represents all these tasks.

I found a great feature for this: Task.WhenAll. However, this is a new feature in .NET 4.5, and I still stick with .NET 4.

So I decided to write my own version until we move on to .NET 4.5. As the question of multithreading often arises (e.g. thread pool material), I'm not sure if my implementation is correct:

public static Task WhenAll(IEnumerable<Task> tasks) { return Task.Factory.StartNew(() => Task.WaitAll(tasks.ToArray())); } 

Functionally this works, I think, but can I get an additional blocked thread for a new task? Or is it inevitable?

Edit: This is how I will 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))); } 
+4
source share
2 answers

Your solution will work fine, but you are correct that it will block the thread all the time.

I think the easiest way to effectively implement WhenAll() in .Net 4.0 is to use ContinueWhenAll() . It performs an action when all the Task from the collection are complete and returns a Task representing this action. Since we want just a Task , we don’t need an action, passing an empty lambda will work:

 public static Task WhenAll(IEnumerable<Task> tasks) { return Task.Factory.ContinueWhenAll(tasks.ToArray(), _ => {}); } 
+9
source

While you are using .Net 4.0 targeting, if you can use VS2012, then a simpler / better option (IMHO) is to use NuGet to install the asynchronous targeting package , and then you can use WhenAll ( TaskEx.WhenAll in this case, since it cannot change the task, within 4.0).

As an important added bonus, you can use async / wait in .Net 4.0 code :

+5
source

Source: https://habr.com/ru/post/1435304/


All Articles