c# - 在c#中同时多次运行一个方法

标签 c# .net multithreading

我有一个返回 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/

相关文章:

c# - 丑陋的类接口(interface)定义

c# - SelectList 没有选择正确的值

c# - 分布式 key 生成是否有 GUID 替代方案?

c# - 我如何在 C# 中处理这副牌(字典)

multithreading - 如何在http中使用多个进程

安卓 : How to detect app killed from recent apps list?

c# - 将字典内容转换为类型 - 枚举数据类型

c# - 如何列出 ASP.NET Core 中的所有配置源或属性?

c# - Cron 表达式在 Azure 中不起作用

java - 公平与不公平