Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 870
eba Avatar asked Mar 08 '11 10:03

eba


2 Answers

You need to keep the reference of the timer in a variable -

public class MyClass
{
    private Timer _timer;

    public void StartTimer()
    {
        _timer =  new Timer(new TimerCallback(y=>{
                            try
                            {
                                Save(Read(DateTime.Now));
                                _timer.Dispose();
                            }
                            catch { 

                            }
                        }),null,100000,10000);
    }



}

Note: This is untested code. Please check if it works and update.

like image 136
Unmesh Kondolikar Avatar answered Sep 20 '22 03:09

Unmesh Kondolikar


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.

like image 26
Jakob Christensen Avatar answered Sep 19 '22 03:09

Jakob Christensen