ラムダを使用した.NETでのタイマーの書き換え


1
var timeToWait = TimeSpan.FromSeconds(20);
var interval = TimeSpan.FromMinutes(5);
var t = new Timer(s =>
    {
        tracker.ProcessAuditLogs();
    }, null, timeToWait, interval);

プログラム/サービスが実行されている限り、タイマーまたは無期限の時間を実行したいと考えています。上記は本番環境で機能しますか?

3

I converted my timer loops to Reactive Extensions a while back to avoid the memory leaks created by event subscriptions and event handlers. A snippet doing the same thing as yours is...

        var timer = Observable
            .Timer(TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(3))
            .Subscribe(q =>
                {   // this executes every 3 seconds in a detached loop 
                    Console.WriteLine("do something here " + q);
                });
        // other work goes here
        GC.KeepAlive(timer);

Of interest here is the last line. This tells the GC that the object should not be garbage collected until it is reached. You can use the same strategy for your event driven timer.

If you wanted a fascinating glimpse into the new garbage collector introduced in 4.5, Maoni Stephens (the lady who actually wrote the GC) made a video that's a 'must see'... http://channel9.msdn.com/posts/Maoni-Stephens-CLR-45-Server-Background-GC