请帮助我理解如何在第一次尝试失败后停止在WPF DispatcherTimer的MethodOne()
事件处理程序中执行dispatcherTimer.Tick
的尝试。
TimeSpan ts = new TimeSpan(0, 0, 5);
DispatcherTimer dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = ts;
dispatcherTimer.Start();
...
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
try
{
MethodOne()
}
catch (Exception)
{
// Here I would like prevent code from trying to execute MethodOne()
}
}
我想设置一些锁定或停止计时器,但是尝试这样做我遇到了Try-Catch构造中其他代码的可见性问题而不确定如何正确克服它。
答案 0 :(得分:3)
这就是“发件人”参数的用途:
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
try
{
MethodOne()
}
catch (Exception)
{
(sender as DispatcherTimer).Stop();
}
}