【发布时间】:2012-10-19 19:31:11
【问题描述】:
我有这个静态类,它包含一个静态变量(一个简单的 int)。我在线程的Run() 方法中实现了lock(),所以没有其他线程可以同时访问这个类,但是变量仍然疯狂,显示重复、异常高的值等等。
这是课程:
public static class ExplorationManager
{
public static int Counter = 0;
public static void ExplorerMaker(List<int[]> validPaths, List<string> myParents, string[,] myExplorationMap, List<int[]> myPositions)
{
foreach (var thread in validPaths.Select
(path => new Explorer(myParents, path, myExplorationMap, myPositions)).
Select(explorer => new Thread(explorer.Explore)))
{
thread.Name = "Thread of " + Counter + " generation";
Counter++;
thread.Start();
}
}
}
有没有办法让这个变量“更加”线程安全?
【问题讨论】:
-
发疯了,显示重复,数值高得离谱 - 无法从这段代码中得到真正的解释。
标签: c# multithreading