詳解C#中的定時(shí)器Timer類及其垃圾回收機(jī)制
關(guān)于C# Timer類 在C#里關(guān)于定時(shí)器類就有3個(gè)
C# Timer使用的方法1.定義在System.Windows.Forms里
C# Timer使用的方法2.定義在System.Threading.Timer類里 "
C# Timer使用的方法3.定義在System.Timers.Timer類里
下面我們來具體看看這3種C# Timer用法的解釋:
(1)System.Windows.Forms.Timer
應(yīng)用于WinForm中的,它是通過Windows消息機(jī)制實(shí)現(xiàn)的,類似于VB或Delphi中的Timer控件,內(nèi)部使用API SetTimer實(shí)現(xiàn)的。它的主要缺點(diǎn)是計(jì)時(shí)不精確,而且必須有消息循環(huán),Console Application(控制臺(tái)應(yīng)用程序)無法使用。
(2)System.Timers.Timer
和System.Threading.Timer非常類似,它們是通過.NET Thread Pool實(shí)現(xiàn)的,輕量,計(jì)時(shí)精確,對(duì)應(yīng)用程序、消息沒有特別的要求。
(3)System.Timers.Timer還可以應(yīng)用于WinForm,完全取代上面的Timer控件。它們的缺點(diǎn)是不支持直接的拖放,需要手工編碼。
C# Timer用法實(shí)例
使用System.Timers.Timer類 System.Timers.Timer t = new System.Timers.Timer(10000); //實(shí)例化Timer類,設(shè)置間隔時(shí)間為10000毫秒; t.Elapsed += new System.Timers.ElapsedEventHandler(theout); //到達(dá)時(shí)間的時(shí)候執(zhí)行事件; t.AutoReset = true; //設(shè)置是執(zhí)行一次(false)還是一直執(zhí)行(true); t.Enabled = true; //是否執(zhí)行System.Timers.Timer.Elapsed事件; public void theout( object source, System.Timers.ElapsedEventArgs e) { MessageBox.Show("OK!"); }
Timer的垃圾回收機(jī)制
通常我們需要定時(shí)執(zhí)行一段任務(wù)的時(shí)候,我們就需要定時(shí)器,這時(shí)我們就可以使用c# System.Threading空間中的 Timer定時(shí)器;他是個(gè)異步定時(shí)器,時(shí)間到時(shí)每次都是在線程池中分配一個(gè)線程去執(zhí)行任務(wù)。下面我們來看一個(gè)有趣的例子:
class Program { static void Main(string[] args) { Timer timer = new Timer(TimerCallback,null,0,2000); Console.ReadLine(); } private static void TimerCallback(object o) { Console.WriteLine("in TimerCallback method"); GC.Collect(); } }
當(dāng)我們?cè)赿ebug模式下運(yùn)行該段程序時(shí),正如我們期盼的那樣程序會(huì)每隔2秒鐘執(zhí)行該方法,打印出"in TimerCallback method”,而在release模式下執(zhí)行的時(shí)候,只執(zhí)行一次該方法,字符串只打印一次。在這里我們?cè)谡{(diào)用TimerCallback方法時(shí),強(qiáng)制執(zhí)行垃圾回收器,說明在release模式下,垃圾回收器執(zhí)行回收算法時(shí),首先假設(shè)所有對(duì)象都是可回收的,當(dāng)將Timer對(duì)象賦值給變量t后,t沒有在被引用,因此也就沒有變量引用Timer對(duì)象,所以垃圾收集這時(shí)會(huì)回收Timer對(duì)象。那么為什么在debug模式下卻能夠運(yùn)行能,這跟c#編譯器的優(yōu)化方式有關(guān),在release模式下編譯器做了相關(guān)的優(yōu)化操作。而在debug模式下,timer對(duì)象的生成期是方法的結(jié)束,這樣做也是為了調(diào)試的方便。要不然在調(diào)試時(shí),我們執(zhí)行到Timer timer = new Timer()后想看timer的值時(shí),已經(jīng)被垃圾回收器給回收了,這是我們不期望看到的結(jié)果,編譯器如何處理的,我們可以看看編譯器在release模式下和debug模式下對(duì)上面的代碼編譯后生成的IL對(duì)比我們既知結(jié)果。
release模式編譯生成的IL:
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 32 (0x20) .maxstack 8 IL_0000: ldnull IL_0001: ldftn void GCTest.Program::TimerCallback(object) IL_0007: newobj instance void [mscorlib]System.Threading.TimerCallback::.ctor(object, native int) IL_000c: ldnull IL_000d: ldc.i4.0 IL_000e: ldc.i4 0x7d0 IL_0013: newobj instance void [mscorlib]System.Threading.Timer::.ctor(class [mscorlib]System.Threading.TimerCallback, object, int32, int32) IL_0018: pop IL_0019: call string [mscorlib]System.Console::ReadLine() IL_001e: pop IL_001f: ret } // end of method Program::Main
debug模式下生成的IL:
method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 33 (0x21) .maxstack 4 .locals init ([0] class [mscorlib]System.Threading.Timer timer) IL_0000: nop IL_0001: ldnull IL_0002: ldftn void GCTest.Program::TimerCallback(object) IL_0008: newobj instance void [mscorlib]System.Threading.TimerCallback::.ctor(object, native int) IL_000d: ldnull IL_000e: ldc.i4.0 IL_000f: ldc.i4 0x7d0 IL_0014: newobj instance void [mscorlib]System.Threading.Timer::.ctor(class [mscorlib]System.Threading.TimerCallback, object, int32, int32) IL_0019: stloc.0 IL_001a: call string [mscorlib]System.Console::ReadLine() IL_001f: pop IL_0020: ret } // end of method Program::Main
從生成的IL中我們可以看出在debug模式下,生成IL比在release模式下多了19行紅色字體的IL指令碼,該指令碼的作用是將15行生成的引用Timer對(duì)象的棧上的變量存放到局部變量0中。所以使得在debug模式下該t還被引用,不能夠回收Timer對(duì)象,所以也能出現(xiàn)我們期盼的結(jié)果,那么如何在兩種模式下都能得到我們期盼的結(jié)果呢。我們可以如下操作。
正確的代碼:
class Program { static void Main(string[] args) { Timer timer = new Timer(TimerCallback,null,0,2000); Console.ReadLine(); timer.Dispose(); } private static void TimerCallback(object o) { Console.WriteLine("in TimerCallback method"); GC.Collect(); } }
這時(shí)不管是在release模式下還是debug模式下,都會(huì)每隔2秒鐘調(diào)用我們的回調(diào)方法。
相關(guān)文章
C#動(dòng)態(tài)查詢之巧用Expression組合多條件表達(dá)式的方法和步驟
在C#中,可以使用AndAlso和OrElse方法組合兩個(gè)Expression<Func<T, bool>>類型的表達(dá)式,下面通過實(shí)例代碼給大家分享C#動(dòng)態(tài)查詢之巧用Expression組合多條件表達(dá)式,感興趣的朋友跟隨小編一起看看吧2024-05-05C#基于Socket套接字的網(wǎng)絡(luò)通信封裝
這篇文章主要為大家詳細(xì)介紹了C#基于Socket套接字的網(wǎng)絡(luò)通信封裝本文實(shí)例為大家分享了Java實(shí)現(xiàn)圖片旋轉(zhuǎn)的具體代碼,供大家參考,具體內(nèi)容如下2021-11-11C#通過rabbitmq實(shí)現(xiàn)定時(shí)任務(wù)(延時(shí)隊(duì)列)
工作中經(jīng)常會(huì)有定時(shí)任務(wù)的需求,常見的做法可以使用Timer、Quartz、Hangfire等組件,本文使用C#通過rabbitmq實(shí)現(xiàn)定時(shí)任務(wù)(延時(shí)隊(duì)列),感興趣的可以了解一下2021-05-05