并行运行多个任务(可变数量)并在所有任务完成后继续 [英] Run Multiple Tasks (Variable Number) in parallel and continue when all have finished

查看:50
本文介绍了并行运行多个任务(可变数量)并在所有任务完成后继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要不并行地启动数量"的任务(可变但少于 10 个),并等待它们全部完成,从每个结果中获取.我从他们每个人那里得到结果,保存在一个列表中,然后在最后使用它.

I need to start a "number" of tasks (variable but less than 10) not in parallel, and wait for them all to finish, getting from each the result. I'm getting the result from each of them, saving in a list and then using it in the end.

这是我的代码,它可以工作,但我认为必须有一种更简洁的方法来做到这一点.

Here's my code, and it's working but I think there gotta be a cleaner way to do that.

导致任务数量增加

List<String> Arguments = new List<String> { "AA", "BB", "CC" }; 

List<String> ResultList = new List<String>();  

//**AT LEAST I'VE GOT ONE**

Task<String> Tasks = Task<String>.Factory.StartNew(() =>
{
    return DoSomething(Arguments[0]);
});

ResultList.Add(Tasks.Result);

for (Int32 i = 1; i < Arguments.Count; i++)
{
    ResultList.Add(Tasks.ContinueWith<String>(Result =>
    {
        return DoSomething(Arguments[i]);

    }).Result);
}

//**DO I NEED THIS?? It's working even without!!**
//Tasks.Wait();

for (Int32 i = 0; i < ResultList.Count; i++)
{
    textBox1.AppendText(ResultList[i] + Environment.NewLine + Environment.NewLine);
}

推荐答案

您不需要 Wait() 调用.Task.Result 状态:

You do not need the Wait() call. Documentation for Task<T>.Result states:

访问属性的get访问器会阻塞调用线程,直到异步操作完成;相当于调用了Wait方法.

Accessing the property's get accessor blocks the calling thread until the asynchronous operation is complete; it is equivalent to calling the Wait method.

这篇关于并行运行多个任务(可变数量)并在所有任务完成后继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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