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

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 indicates that timer is useless ..

Therefore, in release mode, Timer only runs once.

(Note that if it is in debug mode, it will always run)

(Note that if you use the Visual Studio debugger, Vs will help you extend the life cycle of the temporary variables... it will continue to run)

(GC. Collect () is called to explicitly execute GC to reflect the situation where T is recycled. In actual situations, explicit call of GC. Collect () is not recommended ())

Code

  Using  System;
Using System. Threading;
Public Static Class Program
{
Public Static Void Main ()
{
// Create a timer object that knows to call our timercallback
// Method once every 2000 milliseconds.
Timer t = New Timer (timercallback, Null , 0 , 2000 );
// Wait for the user to hit <enter>
Console. Readline ();
}
Private Static Void Timercallback (Object O)
{
// Display the date/time when this method got called.
Console. writeline ( " In timercallback: " + Datetime. Now );
// Force a garbage collection to occur for this demo.
GC. Collect ();
}
}

 

To solve this problem, we usually promote the temporary variables to the member variables of the class.

For example, Private Static timer t; (cannot be GC)

There is also private timer t; (if the current class instance is still not GC)

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.