ike*_*kel 3 .net c# multithreading
我有一个返回XML元素的方法,但该方法需要一些时间来完成并返回一个值.
我现在拥有的是什么
foreach (var t in s)
{
r.add(method(test));
}
Run Code Online (Sandbox Code Playgroud)
但这只会在前一个完成之后运行下一个语句.如何让它同时运行?
您应该可以使用此任务:
//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);
}
Run Code Online (Sandbox Code Playgroud)
编辑
上面的代码有一些问题.有关工作版本,请参阅以下代码.在这里,我还重写了循环以使用LINQ进行可读性问题(在第一个循环的情况下,避免tlambda表达式内部的闭包导致问题).
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();
Run Code Online (Sandbox Code Playgroud)
您可以使用Parallel.ForEach哪个将利用多个线程并行执行.您必须确保所有调用的代码都是线程安全的,并且可以并行执行.
Parallel.ForEach(s, t => r.add(method(t));
Run Code Online (Sandbox Code Playgroud)