如何在事件发生时停止Dispatcher

本文关键字:Dispatcher 事件 | 更新日期: 2023-09-27 17:57:47

在事件第一次勾选后,我需要停止连接到Dispatcher的事件。知道怎么做吗?

        int closeSeconds = Convert.ToInt32(utility.GetConfiguration("device", "closePopupPrinterAfterSeconds"));
        var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
        dispatcherTimer.Tick += new EventHandler(dispatcherTimerCheckPopupPrinter_Tick);
        dispatcherTimer.Interval = new TimeSpan(0, 0, closeSeconds);
        dispatcherTimer.Start();

    private void dispatcherTimerCheckPopupPrinter_Tick(object sender, EventArgs e)
    {
        // stop the dispatcherTimer here, so this method will not fire every x seconds
        System.Windows.Threading.Dispatcher displatcher = (System.Windows.Threading.Dispatcher)sender;
    }

如何在事件发生时停止Dispatcher

sender参数强制转换为DispatcherTimer,而不是Dispatcher,并调用其Stop方法,或将其IsEnabled属性设置为false

private void dispatcherTimerCheckPopupPrinter_Tick(object sender, EventArgs e)
{
    var timer = (DispatcherTimer)sender; // not Dispatcher!
    timer.Stop(); // or timer.IsEnabled = false;
}