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)