C# 窗口关闭后仍在调用方法

C# 窗口关闭后仍在调用方法,c#,wpf,C#,Wpf,首先,我不知道这是不是一个愚蠢的问题。我有这个场景,首先我有一个主窗口 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,

首先,我不知道这是不是一个愚蠢的问题。我有这个场景,首先我有一个主窗口

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();

}
refreshData方法执行以下操作:

public void refreshData(object sender, EventArgs e)
{
    Conection c = new Conection();
            //this method just returns 'hello' doesn't affect my problem
    c.sayHello();
}
这个主窗口也有一个按钮,当我点击按钮时,我调用另一个类

private void button1_Click(object sender, RoutedEventArgs e)
{
    ShowData d = new ShowData();
    d.Show();
}
这个类与主窗口非常相似,它也有自己的Dispatcher

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();
}
我使用VisualStudio调试器跟踪对sayHello的调用,问题是当我关闭“ShowData”窗口时,ShowData类对sayHello的调用仍然出现

我没有关好窗户吗?关上窗户后如何停止通话


PS:我尝试在关闭事件时将Dispatchermer设置为null,您需要在窗口关闭事件中使用
stop()
方法停止Dispatchermer

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();
   }
}

您需要使用窗口关闭事件上的
OnWindowClosing
方法停止Dispatcher()

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();
   }
}

你试过阻止它吗@我不知道!我已经试过了,我知道这是件愚蠢的事。。。谢谢@纳蒂比兹,请看看我的答案。你试过阻止它吗@我不知道!我已经试过了,我知道这是件愚蠢的事。。。谢谢@NatyBizz请查看我的答案。谢谢,奇怪的是,对我来说,一个窗口在关闭后被完全破坏,但dispatchtimer是一个新线程。不是windows livesthanks所在的ui线程,但奇怪的是,对我来说,窗口关闭后会被完全破坏,但dispatchtimer是一个新线程。而不是windows所在的ui线程