我已经阅读了一些关于volatile
没有这个关键字的关键字和行为的帖子。
我特别测试了Illustrating usage of the volatile keyword in C#的答案中的代码。运行时,我观察到发布模式下的异常行为,没有附加调试器。到那时为止,没有问题。
因此,据我了解,以下代码永远不应该退出。
public class Program
{
private bool stopThread;
public void Test()
{
while (!stopThread) { } // Read stopThread which is not marked as volatile
Console.WriteLine("Stopped.");
}
private static void Main()
{
Program program = new Program();
Thread thread = new Thread(program.Test);
thread.Start();
Console.WriteLine("Press a key to stop the thread.");
Console.ReadKey();
Console.WriteLine("Waiting for thread.");
program.stopThread = true;
thread.Join(); // Waits for the thread to stop.
}
}
为什么会退出?即使在发布模式下,没有调试器?
更新
改编自Illustrating usage of the volatile 关键字 in C#中的代码。
private bool exit;
public void Test()
{
Thread.Sleep(500);
exit = true;
Console.WriteLine("Exit requested.");
}
private static void Main()
{
Program program = new Program();
// Starts the thread
Thread thread = new Thread(program.Test);
thread.Start();
Console.WriteLine("Waiting for thread.");
while (!program.exit) { }
}
该程序在发布模式后不会退出,没有附加调试器。