首先,我不知道这是一个愚蠢的问题。我有这种情况,首先我有一个主窗口
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_closing事件中将DispatcherTimer设置为null
答案 0 :(得分:2)
您需要使用窗口Stop()
事件上的OnWindowClosing
方法停止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();
}
}