C#/VS2013-为什么这段代码没有调试就失败了?
下面是我编写的一个程序,用于测试基本的线程场景。当我在启用调试的情况下运行它时,它完全按照预期工作C#/VS2013-为什么这段代码没有调试就失败了?,c#,multithreading,visual-studio,debugging,C#,Multithreading,Visual Studio,Debugging,下面是我编写的一个程序,用于测试基本的线程场景。当我在启用调试的情况下运行它时,它完全按照预期工作 using System; using System.Threading; class Program { static bool keepCounting; static void Main(string[] args) { Thread myThread = new Thread(countNumbers); myThread.Nam
using System;
using System.Threading;
class Program
{
static bool keepCounting;
static void Main(string[] args)
{
Thread myThread = new Thread(countNumbers);
myThread.Name = "MyThread";
keepCounting = true;
myThread.Start();
Thread.Sleep(new TimeSpan(0, 0, 1)); // countNumbers() runs for 1 sec.
keepCounting = false;
}
static void countNumbers()
{
Console.WriteLine("{0} beginning count.", Thread.CurrentThread.Name);
long n = 0;
while (keepCounting)
{
n++;
}
Console.WriteLine("Current thread: {0}", Thread.CurrentThread.Name);
Console.WriteLine("Number of iterations: {0}", n);
}
}
然而,当我设置VS来创建发布构建,并使用“启动而不调试”运行它时,请注意,必须采取这两个步骤,否则它仍然会成功——它在打印“MyTrimeSturnCurt”之后,神秘地“在”代码> CuoNoTuNbs.()/<代码>的中间“某处”。它从不超时并将结果打印到控制台窗口
有人能解释这种古怪吗?你的循环while (keepCounting)
{
n++;
}
就语言而言,相当于
var cpu_register = keepCounting;
while (cpu_register)
{
n++;
}
CPU寄存器比内存读取快得多,因此优化器使用第二个版本。这可能适用:特别是你可能必须将
keepCounting
标记为volatile
@MichaelPetch,是的。就是这样。是的,就是这样!使用“volatile”关键字抑制了优化,使我的程序正常工作。你们这些人学识渊博