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

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

这个类与主窗口非常相似,它也有一个自己的 DispatcherTimer

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

我使用 Visual Studio 调试器跟踪对 sayHello 的调用,问题是当我关闭“ShowData”窗口时,从 ShowData 类对 sayHello 的调用仍然出现

我是不是没有正确关闭窗口?关闭窗口后如何停止通话?

PS:我尝试在 on_close 事件中将 DispatcherTimer 设置为 null

最佳答案

您需要在窗口 OnWindowClosing 事件上使用 Stop() 方法来停止 DispatcherTimer。

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

关于c# - 窗口关闭后仍在调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13534583/

相关文章:

c# - 这种字符串操作可以吗?

c# - 从字符串中删除垃圾值

c# - NSubstitute 与 PRISM EventAggregator : Assert that calling a method triggers event with correct payload

c# - 如何获取 WPF 中组框中的控件列表

wpf - 让 Sub 在 WPF 启动时运行

c# - 如何在使用 LINQ 创建的 xml 中将编码作为 ISO-8859-1

c# - 在 C# 中更改 WebBrowser 控件的显示字体?

c# - 异步线程和 session

python - 使用 python 设置背景图像

c# - 在 UWP 中使用 DataTriggerBehavior 更改 ContentTemplate