这是一个正确的.NET 4实施.NET 4.5的WhenAll? [英] Is this a correct .NET 4 implementation for .NET 4.5's WhenAll?

查看:183
本文介绍了这是一个正确的.NET 4实施.NET 4.5的WhenAll?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SignalR。在集线器的功能往往返回任务。我现在有将增加一堆组的连接功能。我想返回表示所有这些任务的任务。



我找到了一个完美的功能:Task.WhenAll。然而,这是.NET 4.5新功能,我仍然停留在.NET 4。



因此,我决定写我自己的版本,直到我们可以移动到.NET 4.5。因为经常有一些注意事项,当涉及到多线程(如线程池的东西),我不知道如果我的实现是正确的:

 公共静态任务WhenAll(IEnumerable的<任务>任务)
{
返回Task.Factory.StartNew(()=> Task.WaitAll(tasks.ToArray()));
}



在功能上,它的工作原理我想,但我没有拿到额外的封锁螺纹新任务?或者,这是不可避免的?



编辑:
这里是我如何与SignalR使用它:

 公共静态任务添加(这IGroupManager groupManager,字符串的ConnectionId,
的IEnumerable<串基团)
{
返回WhenAll(groups.Select(组=> groupManager.Add (ConnectionId之外组)));
}


解决方案

您的解决方案将正常工作,但你说得对,它会阻塞线程的全部时间。



我觉得最简单的方法能够有效地实现 WhenAll()在.NET 4.0是使用 ContinueWhenAll () 。它执行当所有工作期从集合完成一个动作,并返回一个工作表示该动作。因为我们希望这一点工作,我们不需要的动作,传递一个空的lambda将工作:

 公共静态任务WhenAll(IEnumerable的<任务>任务)
{
返回Task.Factory.ContinueWhenAll(tasks.ToArray(),_ => {});
}


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

解决方案

Your solution will work fine, but you're right that it would block a thread the whole time.

I think the simplest way to efficiently implement WhenAll() on .Net 4.0 is to use ContinueWhenAll(). It performs an action when all Tasks from a collection are finished and returns a Task representing that action. Since we want just that Task, we don't need the action, passing an empty lambda will work:

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

这篇关于这是一个正确的.NET 4实施.NET 4.5的WhenAll?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆