这是我编写的用于测试基本线程方案的程序。在启用调试的情况下运行它时,它的工作原理与预期完全相同。
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设置为发布版本,并使用“无需调试开始”运行它时-请注意,必须同时执行这些步骤,否则它仍将成功-神秘地“卡住”了其中的某个位置打印“MyThread起始计数。”之后
countNumbers()
方法的中间,它永远不会超时并将结果打印到控制台窗口。谁能解释这个怪癖?
最佳答案
你的循环
while (keepCounting)
{
n++;
}
就语言而言,相当于
var cpu_register = keepCounting;
while (cpu_register)
{
n++;
}
CPU寄存器比内存读取快很多,因此优化器使用第二个版本。为您带来可预期的不幸结果。
关于c# - C#/VS2013-为什么这些代码在没有调试的情况下会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26695153/