DoEvents:Dispatcher.Invoke与PushFrame

时间:2014-08-22 07:46:00

标签: 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;
}

来源:MSDN Library

阻止调用方式:

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

来源:Blog

哪个更好,这两个解决方案之间是否有任何功能差异?

更新:这是代号内联的第二位,如第一项所示,使其更短:

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

1 个答案:

答案 0 :(得分:5)

你回答了自己的问题。你选择的并不重要,因为两者在后台都是一样的。

两者都遇到了这个:

While (dispatcherFrame.Continue)
{
  Dispatcher.GetMessage();
  Dispatcher.TranslateAndDispatch();
}

然而,由于您不需要创建空委托,因此PushFrame更好一些。