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.
}
}
なぜ終了するのですか?デバッガなしでリリースモードでも?
アップデート
C# での volatile キーワードの使用例のコードの適応。
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) { }
}
このプログラムは、デバッガーが接続されていない場合、リリース モードで終了しません。