我有一个返回 XML 元素的方法,但该方法需要一些时间才能完成并返回一个值。
我现在拥有的是
foreach (var t in s)
{
r.add(method(test));
}
但这只会在前一个语句完成后运行下一个语句。如何让它同时运行?
最佳答案
您应该能够为此使用任务:
//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
导致问题)。
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# - 在c#中同时多次运行一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8815147/