【发布时间】:2009-09-22 17:45:22
【问题描述】:
我通常会按照以下思路编写代码:
public class MyClass
{
static bool m_stop = false;
public static void Main()
{
var th = new Thread(DoStuff);
th.Start();
Console.ReadLine();
m_stop = true;
th.Join();
}
private static void DoStuff()
{
while( !m_stop )
{
// do things here
}
}
}
...而且我总是同步对变量 m_stop 的访问,只是出于习惯。我想知道是否真的有必要这样做(假设在 DoStuff() 中运行一个或两个额外的循环不会有任何伤害)。如果代码完全像这样执行,可能发生的最坏情况是什么?我曾考虑过为 m_stop 使用 volatile 关键字,但我不确定是否有必要这样做。有谁知道吗?
【问题讨论】:
标签: c# thread-safety