排序任务到completition秩序 [英] Sort Tasks into order of completition

查看:237
本文介绍了排序任务到completition秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到乔恩斯基特作专题演讲一年多前,他表现出的C#5片段,将采取的任务列表,并在他们完成了顺序返回。

I saw Jon Skeet give a talk a year or so ago where he showed a snippet of C# 5 that would take a list of Tasks and return them in the order they completed.

它利用异步电动机/等待和WhenAny,是挺漂亮的,但我不能为我的生活还记得它是如何工作的。现在我需要它。

It made use of async/await and WhenAny and was quite beautiful but I can't for the life of me remember how it worked. Now I have need for it.

我希望能弄清楚如何创建一个类似下面的签名的方法。

I'm hoping to figure out how to create a method with a signature similar to this..

Task<IEnumerable<T>> InOrderOfCompletion<T>(IEnumerable<T> tasks) where T : Task

和可以用作如下:

public async Task<int> DelayedInt(int i)
{
    await Task.Delay(i*100);
    return i;
}

[Test]
public async void Test()
{
    Task<int>[] tasks = new[] {5, 7, 1, 3, 2, 6, 4}.Select(DelayedInt).ToArray();
    IEnumerable<Task<int>> ordered = await InOrderOfCompletion(tasks);

    Assert.That(ordered.Select(t => t.Result).ToArray(), Is.EqualTo(new [] {1,2,3,4,5,6,7}));
}

我已经想出了下面的,但我记得感觉并不那么简单。

I've come up with the following but it doesn't feel as simple as I remember

    async Task<IEnumerable<T>> InOrderOfCompletion<T>(IEnumerable<T> tasks) where T : Task
    {
        HashSet<Task> taskSet = new HashSet<Task>(tasks);
        List<T> results = new List<T>();
        while(taskSet.Count > 0)
        {
            T complete = (T) await Task.WhenAny(taskSet);
            taskSet.Remove(complete);
            results.Add(complete);
        }
        return results;
    }

难道还有人记得知道我指的是代码片段或如何可以改进?

Do anyone remember know the snippet I'm referring to or how this can be improved upon?

推荐答案

<一个href=\"https://$c$cblog.jonskeet.uk/2012/01/16/eduasync-part-19-ordering-by-completion-ahead-of-time/\"相对=nofollow>乔恩斯基特,的斯蒂芬Toub ,<一个href=\"http://dotnetapis.com/pkg/Nito.AsyncEx/3.0.1/net45/doc/Nito.AsyncEx.TaskExtensions/OrderByCompletion''1(System.Collections.Generic.IEnumerable(System.Threading.Tasks.Task(''0)))\"相对=nofollow>我的都略有不同的方法。我的是 如果你不想写自己的。

Jon Skeet, Stephen Toub, and I all have slightly different approaches. Mine is available via NuGet if you don't want to write your own.

其实,关键是要的避免 Task.WhenAny ,因为这会变成算法从O(N)为O(N ^ 2 )。

Actually, the key is to avoid Task.WhenAny because that will turn the algorithm from O(N) into O(N^2).

这篇关于排序任务到completition秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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