调度程序.禁用处理 - 无效操作异常

本文关键字:无效 操作 异常 处理 调度程序 | 更新日期: 2023-09-27 18:34:38

我正在研究Dispatcher.DisableProcessing((作为暂停和恢复UI渲染的一种手段,我正在尝试在没有using(({}语句的情况下使用它。

它抛出 InvalidOperationException - 调度程序处理已暂停,但消息仍在处理中。

问题:为什么抛出此异常?有什么方法可以在 using(({} 语句之外使用它吗?

提前感谢!

-

编辑以包括测试代码-

工作流程:

成功运行 OnPauseButtonClick 代码后,该异常仍然发生。

public class MainWindow: Window
{
    public MainWindow()
    {
        Initialize();
    }
    private DispatcherProcessingDisabled x;
    public void OnPauseButtonClick(object sender, RoutedEventArgs e)
    {
        x = Dispatcher.DisableProcessing();
    }
    public void OnTestButtonClick(object sender, RoutedEventArgs e)
    {
        Timer t = new Timer(TimerCallback, null, 0, 1000);
    }
    public void TimerCallback(object o)
    {
        //all codes were commented out
    }
}

调度程序.禁用处理 - 无效操作异常

好的,

所以我找到了调度程序抛出异常的位置。

    [UIPermissionAttribute(SecurityAction.LinkDemand,Unrestricted=true)]
    [SecurityCritical]
    public static void PushFrame(DispatcherFrame frame)
    {
        if(frame == null)
        {
            throw new ArgumentNullException("frame");
        }
        Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
        if(dispatcher._hasShutdownFinished) // Dispatcher thread - no lock needed for read
        {
            throw new InvalidOperationException(SR.Get(SRID.DispatcherHasShutdown));
        }
        if(frame.Dispatcher != dispatcher)
        {
            throw new InvalidOperationException(SR.Get(SRID.MismatchedDispatchers));
        }
        //here
        if(dispatcher._disableProcessingCount > 0) 
        {
            throw new InvalidOperationException(SR.Get(SRID.DispatcherProcessingDisabled));
        }
        dispatcher.PushFrameImpl(frame);
    }

这里

根据堆栈跟踪,此函数由 Application.RunInternal 调用。应用程序将工作推送到调度程序中,但由于它被禁用而无法执行此操作。我的猜测是,这项工作是按下按钮的效果,然后是按钮聚焦时的发光效果,但我不能确定。