c# - 了解 WPF 中提供的 DispatcherPriority 枚举的真实行为

标签 c# wpf multithreading dispatcher

what each enum does 上有包含定义的文档.但是我怎样才能在实践中演示/看到这个呢?我怎么可能知道什么时候使用哪个优先级?

这是我创建的一些代码,试图查看优先级如何影响排序,它为我提供了排序正确的证据(第一个循环迭代将向调度队列添加一个 SystemIdle 枚举),但它仍然最后添加到字符串中

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

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

最佳答案

Prism Framework包装 DispatcherDefaultDispatcher 使用 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 线程上运行任何实际逻辑,我就建议您这样做。

如果您出于某种原因想要在 UI 线程上运行“快速”逻辑,您可以遵循建议 here并坚持使用 Background 的值。

我仔细研究了一下,在 NuGet's source 中发现了一些用法他们出于各种原因使用 SendNormalBackgroundApplicationIdle 但在我的 WPF 开发中我从未有过将 DispatcherPriority 的使用微调到这个程度。

关于c# - 了解 WPF 中提供的 DispatcherPriority 枚举的真实行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33701510/

相关文章:

c# - 如何使用 C# 中的代码更改网络设置(IP 地址、DNS、WINS、主机名)

c# - XAML 中图标格式的最佳实践(SVG、路径数据点、几何/XAML 或字体)

java - GWT:多线程

c# - 热从另一个线程调用方法或从另一个线程触发事件,该事件在主线程上处理

java - 在原子变量上使用 volatile

c# - 将后台工作人员的数量限制为两个,并在添加时完成工作

c# - 获取子进程的形式

c# - 使用 lambda 表达式创建带反射的对象

wpf - 基于现有样式的 MahApps 设置样式有奇怪的输出

c# - XAML 中的泛型