Why DispacherTimer.Tick event occurs two times?

621 views Asked by At

I use DispacherTimer to auto-save a file. The code is like the following:

void beginAutoSave()
{
    _autoSaveDispacherTimer = new DispatcherTimer();
    _autoSaveDispacherTimer.Interval = TimeSpan.FromMinutes(1);
    _autoSaveDispacherTimer.Tick += new EventHandler(onAutoSaveTick);
    _autoSaveDispacherTimer.Start();
}

void onAutoSaveTick(object sender, EventArgs e)
{
    // I save the file with a randomly generated file name
}

I call beginAutoSave() just once. The problem is that in each Tick event, two different files are being saved. In other words, onAutoSaveTick(...) method is called twice. The call stack seems to be the same in both calls. Where is my mistake?

Any help is appreciated. Thanks.

1

There are 1 answers

1
Rohit Vats On

onAutoSaveTick will be called after every one minute. You need to stop explicitly timer if you want to execute it once.

From MSDN documentation -

The Tick event fires after the time specified in Interval has elapsed. Tick continues firing at the same Interval until the Stop method is called.

Do this in tick handler itself:

void onAutoSaveTick(object sender, EventArgs e)
{
    // I save the file with a randomly generated file name
    _autoSaveDispacherTimer.Stop();
}