dimanche 22 avril 2018

Stop a DispatcherTimer in a service class when application is closed

I am wondering what is a proper pattern for handling stopping of the DispatcherTimer when the application that uses this instance is closed. As the DispatcherTimer is not stopped, the app is not fully closed & disposed.

I can only think of the following:

public class ReminderServiceClass : IDisposable
{

    public ReminderServiceClass ()
    {

        this.Timer = new DispatcherTimer()
        {
            Interval = TimeSpan.FromMinutes(value: 10)
        };
        this.Timer.Tick += this.Timer_Tick;
        this.Timer.Start();
    }


     public void Dispose()
    {
        MessageBox.Show("Dispozed");
        this.Timer.Stop();
    }
}

and then in the view model / user control class call the reminderService.Dispose() method (or use it within a using block, however it doesn't seem right for 'ReminderService' class).

However, I don't like this approach because this means that ViewModels, User Controls or other classes need to be aware that there is a DispatcherTimer and are responsible for remembering that a Dispose needs to be called.

Is there any pattern which allows a more 'self-contained' approach for classes which use DispatcherTimer? Or perhaps I should use something else instead?

Thanks!

Aucun commentaire:

Enregistrer un commentaire