【问题标题】:How to stop DispatcherTimer from inside Try - Catch?如何从 Try - Catch 中停止 DispatcherTimer?
【发布时间】:2010-01-20 16:25:06
【问题描述】:

请帮助我了解如何在第一次尝试不成功后停止在 WPF DispatcherTimer 的 dispatcherTimer.Tick 事件处理程序中执行 MethodOne() 的尝试。

        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 构造中看到其他代码的问题,并且不知道如何正确克服它。

【问题讨论】:

    标签: c# wpf timer try-catch dispatcher


    【解决方案1】:

    这就是“发件人”参数的用途:

    private void dispatcherTimer_Tick(object sender, EventArgs e)
    {           
        try
        {
           MethodOne()
        }
        catch (Exception)
        {
            (sender as DispatcherTimer).Stop();
        }  
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      相关资源
      最近更新 更多