c# - C#/VS2013-为什么这些代码在没有调试的情况下会失败?

标签 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.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/

相关文章:

java - Thread.sleep() 没有按预期触发

c++ - 为什么在我启动新线程时 Valgrind 会出现段错误

visual-studio - 如何在构建过程中检查引用

c# - 具有中央数据库的多用户环境中的 Entity Framework 数据更新

c# - 可移植类库中的 MvvmLight - 如何进行单元测试

c++ - 异步函数调用,带有检查进度的方法

visual-studio - 在Visual Studio C#中输入Unicode数据

windows - 如何在 Visual Studio 中为 xamarin.forms 应用程序生成 .ipa 文件

c# - 只有一位小数的字符串格式?

c# - DateTimePicker 的初始值错误