在C#中同时运行一个方法多次 [英] run a method multiple times simultaneously in c#

查看:710
本文介绍了在C#中同时运行一个方法多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回XML元素的方法,但是该方法需要一些时间才能完成并返回一个值.

I have a method that returns XML elements, but that method takes some time to finish and return a value.

我现在拥有的是

foreach (var t in s)
{
    r.add(method(test));
}

,但这仅在上一个语句完成后才运行下一个语句.如何使其同时运行?

but this only runs the next statement after previous one finishes. How can I make it run simultaneously?

推荐答案

您应该可以使用以下任务:

You should be able to use tasks for this:

//first start a task for each element in s, and add the tasks to the tasks collection
var tasks = new List<Task>();
foreach( var t in s)
{
    tasks.Add(Task.Factory.StartNew(method(t)));
}

//then wait for all tasks to complete asyncronously
Task.WaitAll(tasks);

//then add the result of all the tasks to r in a treadsafe fashion
foreach( var task in tasks)
{
  r.Add(task.Result);
}

编辑 上面的代码有一些问题.请参见下面的代码以获取有效版本.在这里,我还重写了循环,以使用LINQ来解决可读性问题(在第一个循环的情况下,要避免lambda表达式内的t闭合会导致问题).

EDIT There are some problems with the code above. See the code below for a working version. Here I have also rewritten the loops to use LINQ for readability issues (and in the case of the first loop, to avoid the closure on t inside the lambda expression causing problems).

var tasks = s.Select(t => Task<int>.Factory.StartNew(() => method(t))).ToArray();

//then wait for all tasks to complete asyncronously
Task.WaitAll(tasks);

//then add the result of all the tasks to r in a treadsafe fashion
r = tasks.Select(task => task.Result).ToList();

这篇关于在C#中同时运行一个方法多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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