CLR via C # Reading Notes 2-1 problems caused by Compiler Optimization

Source: Internet
Author: User

One major difference between the debug and release modes of the DOTNET project is whether the compiler optimization is enabled.

Due to the use of editor Optimization in release, some of the original operations are normal.CodeThere will be problems.

The following code is as follows:

 

  Internal     Static     Class  Strangebehavior
{
// As you'll see later, mark this field as volatile to fix the problem
Private Static Boolean s_stopworker = False ;
Public Static Void Main ()
{
Console. writeline ( " Main: lew.worker run for 5 seconds " );
Thread t = New Thread (worker );
T. Start ();
Thread. Sleep ( 5000 );
S_stopworker = True ;
Console. writeline ( " Main: waiting for worker to stop " );
T. Join ();
}
Private Static Void Worker (Object O)
{
Int32 x = 0 ;
While ( ! S_stopworker) x ++ ;
Console. writeline ( " WORKER: stopped when x = {0} " , X );
}
}

 

Compile and run in debug mode and you will findProgramIt's normal.

Compile and run the program in release mode and you will find that the program is in an endless loop.

This is because the compiler considers s_stopworker as a constant in optimization mode (false if not true)

When s_stopworker is set to false, the compiler considers that while (true) always enters an endless loop.

But when s_stopworker is true, the editor will ignore the while (! S_stopworker )...

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.