Are there risks to optimizing code in C#?

后端 未结 8 900
粉色の甜心
粉色の甜心 2020-12-18 18:53

In the build settings panel of VS2010 Pro, there is a CheckBox with the label \"optimize code\"... of course, I want to check it... but being unusually cautious, I asked my

8条回答
  •  感动是毒
    2020-12-18 19:39

    It is possible that some bugs will occur when running in release mode that do not otherwise occur. The infamous "non-volatile flag" comes to mind:

    flag = false;
    
    Thread t = new Thread(
       o =>
       {
            while(!flag)
            {
               // do stuff
            }
       });
    t.Start();
    
    // main thread does some work
    
    flag = true;
    t.Join(); // will never return in release mode if flag is not volatile
    

    This happens because of compiler optimizations, as the flag variable gets cached by the core of thread t and thus it cannot see the updated value of flag.

提交回复
热议问题