【发布时间】:2021-08-12 03:11:04
【问题描述】:
我正在使用下面的代码并在 foeach 循环中使用 Task.Run 以便每个循环都可以并行运行,因为我在 foreach 循环中有一些逻辑需要一些时间,但我面临的问题是 tContext.SecondNodeId =其他节点;有时打印为 10 或 11 ,我想按前 10 后 11 的顺序打印,因为我还有一些代码,这些值对逻辑很重要。
class Program
{
static void Main(string[] args)
{
TempData tContext = new TempData();
var nodes = new List<int>() { 1, 2, 3, 4, 5, 6 };
var otherNodes = new List<int> { 10, 11 };
foreach (var node in nodes)
{
tContext.firstNodeId = node;
List<Task> tasks = new List<Task>();
foreach (var otherNode in otherNodes)
{
Task t = Task.Run(() =>
{
tContext.SecondNodeId = otherNode;
Console.WriteLine("First Node id is" + tContext.firstNodeId + "Second Node Id is " + tContext.SecondNodeId);
// I have some long running code which uses first node and second node id.
});
tasks.Add(t);
}
Task.WaitAll(tasks.ToArray());
}
}
}
请提出一种实现方法。
下面是输出。
【问题讨论】:
标签: c# .net multithreading thread-safety threadpool