Search code examples
.netcallbacktimerdispose

Can I dispose a Threading.Timer in its callback?


I'm using Threading.Timer, like:

new Timer(new TimerCallback(y=>
{
    try
    {
        Save(Read(DateTime.Now));
        // here i want to dispose this timer
    }
    catch
    {                          
    }
}),null,100000,10000);

How can I dispose this timer inside of a callback. or workaround? Update: Let me explain the situation. I want to try to call the method "Save", while it throws an exception. If it works, I need to stop the timer.


Solution

  • Try this:

    Timer timer = null;
    timer = new Timer(new TimerCallback(y =>
    {    
        try    
        {
            Save(Read(DateTime.Now));        
            // here i want to dispose this timer
            timer.Dispose();    
        }    
        catch    
        {    
        }
    }));
    timer.Change(10000, 10000);
    

    EDIT:

    I changed the above code slightly according to Chuu's suggestion. Note that if the TimerCallback is called simultanuously by different timer events, Timer.Dispose may end up being called several times. Luckily the Timer does not care if it is being disposed of several times.