You need to know the garbage collection mechanism of C # Timer.

Source: Internet
Author: User
Tags mscorlib

Usually we need a timer when we have to perform a task on a regular basis, and then we can use the timer timer in C # system.threading space; He is an asynchronous timer, and every time it is assigned a thread in the inline pool to perform the task. Let's look at an interesting example:

Class program    {        static void Main (string[] args)        {            Timer timer = new timer (timercallback,null,0,2000); C5/>console.readline ();        }        private static void TimerCallback (object o)        {            Console.WriteLine ("In TimerCallback Method");            Gc. Collect ();                    }    }

When we run the program in debug mode, as we expect, the program executes the method every 2 seconds, prints "in TimerCallback method", and executes it in release mode only once, and the string is printed only once. Here we force the garbage collector when invoking the TimerCallback method, stating that in release mode, when the garbage collector performs the reclamation algorithm, it assumes that all objects are recyclable, and when the timer object is assigned to the variable T, T is not referenced. Therefore, there is no variable to reference the Timer object, so garbage collection will then recycle the timer object. So why is it possible to run in debug mode, which is related to the optimization of the C # compiler, and the compiler has done some optimizations in release mode. In debug mode, the timer object generation period is the end of the method, which is also for debugging convenience. Otherwise when debugging, we execute to the timer timer = new timer () to see the value of the timer, has been recycled by the garbage collector, which we do not expect to see the results of the compiler, how to handle, We can look at the Il contrast generated by the compiler in release mode and debug mode for the above code, we know the result.

Release mode compiles the generated IL:

1. methodPrivateHidebysigStatic voidMain (string[] args) CIL managed2 {3 . EntryPoint4   //Code Size (0x20)5. maxstack86 Il_0000:ldnull7Il_0001:ldftnvoidGctest.program::timercallback (Object)8Il_0007:newobj instancevoid[mscorlib] System.threading.timercallback::.ctor (Object,9Nativeint)Ten Il_000c:ldnull OneIL_000d:ldc.i4.0 AIL_000e:ldc.i40x7d0 -Il_0013:newobj instancevoid[mscorlib] System.threading.timer::.ctor (class[Mscorlib]system.threading.timercallback, -                                                                              Object, the Int32, - int32) - Il_0018:pop -Il_0019:callstring[Mscorlib]system.console::readline () + Il_001e:pop - Il_001f:ret +}//end of Method Program::main

Il generated in debug mode:

1MethodPrivateHidebysigStatic voidMain (string[] args) CIL managed2 {3 . EntryPoint4   //Code Size (0x21)5. maxstack46. Locals init ([0]class[Mscorlib]system.threading.timer Timer]7 Il_0000:nop8 Il_0001:ldnull9Il_0002:ldftnvoidGctest.program::timercallback (Object)TenIl_0008:newobj instancevoid[mscorlib] System.threading.timercallback::.ctor (Object, OneNativeint) A Il_000d:ldnull -IL_000e:ldc.i4.0 -IL_000f:ldc.i40x7d0 theIl_0014:newobj instancevoid[mscorlib] System.threading.timer::.ctor (class[Mscorlib]system.threading.timercallback, -                                                                              Object, - Int32, - int32)il_0019:stloc.0 -Il_001a:callstring[Mscorlib]system.console::readline () + Il_001f:pop A Il_0020:ret at}//end of Method Program::main

From the generated IL we can see that in debug mode, the generated IL is more than 19 lines of the red font in the release mode of the Il script, the role of this script is 15 lines generated reference timer object on the stack of the variables stored in the local variable 0. So in debug mode the T is also referenced, not able to reclaim the timer object, so we can also appear the results we expect, then how to get the results we expect in both modes. We can do the following.

The correct code:

1   class Program2     {3         Static voidMain (string[] args)4         {5Timer timer =NewTimer (TimerCallback,NULL,0, -);6         7 console.readline ();8 timer. Dispose ();9         }Ten  One         Private Static voidTimerCallback (Objecto) A         { -Console.WriteLine ("In TimerCallback method"); -  the GC. Collect (); -  -              -         } +}

The callback method is called every 2 seconds, either in release mode or in debug mode.

You need to know the garbage collection mechanism of C # Timer.

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.