理解WPF

时间:2015-11-13 20:49:27

标签: c# wpf multithreading dispatcher

what each enum does上有关于定义的文档。但是我怎么能在实践中演示/看到这个?我怎么可能知道何时使用哪个优先级?

这里是我创建的一些代码,试图了解priorty如何影响排序,它为我提供了排序正确的证明(第一次循环迭代将SystemDdle枚举添加到调度队列),但它仍然被添加到字符串最后

private void btn_Click(object sender, RoutedEventArgs e)
    {
        StringBuilder result = new StringBuilder();
        new Thread(() =>
            {

                var vals = Enum.GetValues(typeof(DispatcherPriority)).Cast<DispatcherPriority>().Where(y => y >= 0).ToList();
                vals.Reverse();
                vals.ForEach(x =>
                    { 
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            result.AppendLine(string.Format("Priority: {0} Enum:{1}", ((int)x), x.ToString()));
                        }), x);
                    });


            }).Start();

        ShowResultAsync(result, 2000);
    }

    private async void ShowResultAsync(StringBuilder s, int delay)
    {
        await Task.Delay(delay);
        MessageBox.Show(s.ToString());
    }

enter image description here

并且输出顺序保持不变,即使列表被反转(在vals被分配后添加此行):

vals.Reverse();

再一次,在确定我应该分配哪个调度优先级时,还有什么我可以使用的吗?

1 个答案:

答案 0 :(得分:0)

Prism FrameworkDefaultDispatcher包裹Dispatcher使用Normal优先级。这应该是几乎所有应用场景的基础。

/// <summary>
/// Wraps the Application Dispatcher.
/// </summary>
public class DefaultDispatcher : IDispatcherFacade
{
    /// <summary>
    /// Forwards the BeginInvoke to the current application's <see cref="Dispatcher"/>.
    /// </summary>
    /// <param name="method">Method to be invoked.</param>
    /// <param name="arg">Arguments to pass to the invoked method.</param>
    public void BeginInvoke(Delegate method, object arg)
    {
        if (Application.Current != null)
        {
            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, method, arg);
        }
    }
}

只要您没有在UI线程上运行任何实际逻辑,我建议您这样做。

如果你出于某种原因想要跑步&#34;快速&#34; UI线程上的逻辑,您可以遵循建议here并坚持使用值Background

我确实对它进行了一些调查,我在NuGet's source中找到了一些使用SendNormalBackgroundApplicationIdle的用法,原因各种各样但是在我的WPF开发中,我从来没有必要在这个程度上微调DispatcherPriority的使用。