DoEvents:Dispatcher.Invoke与PushFrame

ygo*_*goe 5 wpf dispatcher

最近,我发现了一种方法,该方法执行调度程序队列中的所有待处理消息,直到指定优先级为止。我之前已经有这样的代码,但是它们使用完全不同的方法。这两个都是:

PushFrame方式:

/// <summary>
/// Enters the message loop to process all pending messages down to the specified
/// priority. This method returns after all messages have been processed.
/// </summary>
/// <param name="priority">Minimum priority of the messages to process.</param>
public static void DoEvents(
    DispatcherPriority priority = DispatcherPriority.Background)
{
    DispatcherFrame frame = new DispatcherFrame();
    Dispatcher.CurrentDispatcher.BeginInvoke(
        priority,
        new DispatcherOperationCallback(ExitFrame), frame);
    Dispatcher.PushFrame(frame);
}

private static object ExitFrame(object f)
{
    ((DispatcherFrame) f).Continue = false;
    return null;
}
Run Code Online (Sandbox Code Playgroud)

来源:MSDN库

阻止调用方式:

private static Action EmptyDelegate = delegate { };

/// <summary>
/// Processes all pending messages down to the specified priority.
/// This method returns after all messages have been processed.
/// </summary>
/// <param name="priority">Minimum priority of the messages to process.</param>
public static void DoEvents2(
    DispatcherPriority priority = DispatcherPriority.Background)
{
    Dispatcher.CurrentDispatcher.Invoke(EmptyDelegate, priority);
}
Run Code Online (Sandbox Code Playgroud)

资料来源:网志

哪个更好,两个解决方案之间在功能上有什么不同?

更新:这是第二个与内联代表的内联,与第一个一样,使其更短:

/// <summary>
/// Processes all pending messages down to the specified priority.
/// This method returns after all messages have been processed.
/// </summary>
/// <param name="priority">Minimum priority of the messages to process.</param>
public static void DoEvents2(
    DispatcherPriority priority = DispatcherPriority.Background)
{
    Dispatcher.CurrentDispatcher.Invoke(new Action(delegate { }), priority);
}
Run Code Online (Sandbox Code Playgroud)

dev*_*hog 5

您回答了自己的问题。选择哪个都没关系,因为两者在后台执行相同的操作。

两者都遇到这个:

While (dispatcherFrame.Continue)
{
  Dispatcher.GetMessage();
  Dispatcher.TranslateAndDispatch();
}
Run Code Online (Sandbox Code Playgroud)

但是,PushFrame更好一些,因为您不需要创建空的委托。