Dispatcher.DisableProcessing - InvalidOperationException

时间:2014-12-18 09:15:02

标签: c# .net wpf dispatcher

我正在调查Dispatcher.DisableProcessing()作为暂停和恢复UI呈现的方法,我试图在没有using(){}语句的情况下使用它。

它抛出InvalidOperationException - Dispatcher处理已被暂停但消息仍在处理中。

问题: 为什么抛出这个异常? 有没有办法可以在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
    }
}

1 个答案:

答案 0 :(得分:0)

好的,所以我找到了Dispatcher抛出异常的地方。

    [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);
    }

Here

根据stacktrace,Application.RunInternal调用此函数。应用程序将一个工作推送到调度程序中,因为它已被禁用而无法执行。我的猜测是,这项工作是推动按钮的效果,然后是按钮聚焦时的发光效果,但我无法确定。