Naty Bizz
Naty Bizz

Reputation: 2342

Window still calling method after being closed

First of all I don't know if this is a dumb question. I have this scenario, first I have a main window

public MainWindow()
{

    InitializeComponent();
    //dt is a System.Windows.Threading.DispatcherTimer variable
    dt = new System.Windows.Threading.DispatcherTimer();
    dt.Interval = new TimeSpan(0, 0, 0, 0, 30000);
    dt.Tick += new EventHandler(refreshData);

    dt.Start();

}

the refreshData method does this:

public void refreshData(object sender, EventArgs e)
{
    Conection c = new Conection();
            //this method just returns 'hello' doesn't affect my problem
    c.sayHello();
}

This main window also has a button, when I click on the button I call to another class

private void button1_Click(object sender, RoutedEventArgs e)
{
    ShowData d = new ShowData();
    d.Show();
}

This class is pretty much similar to the main window, it has an own DispatcherTimer too

public ShowData()
{
    InitializeComponent();

    dt = new System.Windows.Threading.DispatcherTimer();
    dt.Interval = new TimeSpan(0, 0, 0, 0, 30000);
    dt.Tick += new EventHandler(refreshData);

    dt.Start();
}

public void refreshData(object sender, EventArgs e)
{
    Conection c = new Conection();
    c.sayHello();
}

I track the calls to sayHello with the visual studio debugger, the problem is when I close the 'ShowData' window, the call to sayHello from the ShowData class is still appearing

Am I not closing the window properly? how can I stop the calls after closing the window?

PS: I tried setting the DispatcherTimer to null in on_closing event

Upvotes: 2

Views: 2015

Answers (1)

dknaack
dknaack

Reputation: 60468

You need to stop the DispatcherTimer using the Stop() method on your window OnWindowClosing event.

public class MainWindow : Window
{
   DispatcherTimer MyTimer;

   public MainWindow()
   {
      InitializeComponent();

      MyTimer = new System.Windows.Threading.DispatcherTimer();
      MyTimer.Interval = new TimeSpan(0, 0, 0, 0, 30000);
      MyTimer.Tick += new EventHandler(refreshData);
      // Start the timer
      MyTimer.Start();
   }

   public void OnWindowClosing(object sender, CancelEventArgs e) 
   {
       // stop the timer
       MyTimer.Stop();
   }

   public void refreshData(object sender, EventArgs e)
   {
      Conection c = new Conection();
      c.sayHello();
   }
}

Upvotes: 4

Related Questions