TPL订购任务结果 [英] TPL Orderring Task results

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

问题描述

有什么方法可以按顺序收集任务结果.对于前,我有一个数组的100个项目(值0-100).我创建10个任务,每个任务处理数组(1-10,10-20,...)中的10个项目,并开始并行运行.现在,我需要一种机制来收集所有任务的结果 为了.像来自Task1,taks2,Task3 ..... etc

Is there any way to gather task results in order. For ex, i have an array of 100 items (values 0-100). I create 10 tasks each process 10 items from array (1-10,10-20,...)and starts running parallel. Now, i need a mechanism to gather results from all tasks in order. like results from Task1,taks2,Task3 .....etc

推荐答案

只需保存对每个任务的引用即可识别并使用Task.WaitAll方法等待所有任务完成,然后按照您喜欢的顺序来评估每个任务的result属性:

Just save a reference to each task to be able to identify it and use the Task.WaitAll method to wait for all tasks to complete and then evaliate the result property of each of the tasks in your preferred order:

            Task<int> t1 = Task.Run(()=> { /* process 0-10*/ return 0; });
            Task<int> t2 = Task.Run(() => { /* process 11-20*/ return 1; });
            Task<int> t3 = Task.Run(() => { /* process 21-30*/ return 2; });
            //...

            Task.WaitAll(t1, t2, t3);

            int firstResult = t1.Result;
            int secondResult = t2.Result;
            //...


如何:从任务中返回值: https://msdn.microsoft.com/zh-CN/library/dd537613(v=vs.110).aspx

希望有帮助.

请记住,通过将有用的帖子标记为答案来关闭话题,然后在遇到新问题时开始新话题.请不要在同一线程中问几个问题.

Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question. Please don't ask several questions in the same thread.


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

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