首先我不知道这是不是一个愚蠢的问题。我有这样的场景,首先我有一个主窗口
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/