2015-11-13 126 views
4

有关于what each enum does定义的文档。但是我怎么能够在实践中演示/看到这个?我怎么可能知道什么时候使用哪个优先级?了解WPF中提供的DispatcherPriority枚举的真实行为

下面是我创建的一些代码,试图了解priorty如何影响排序,它为我提供了排序正确的证据(第一个循环迭代已将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(); 

因此,再次确定我应该分配哪些分派优先级时可以使用更多内容吗?

+0

可能的重复http://stackoverflow.com/q/18378345/2562358 –

+0

是的,我见过它。但是,这个答案中的两个环节都不够。 – William

回答

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线程上运行任何实际的逻辑,我会建议这样做。

如果您因为某种原因想要在UI线程上运行“快速”逻辑,您可以按照建议here并坚持使用值Background

我没看进去一点,我发现了一些用法在NuGet's source,他们使用各种原因SendNormalBackgroundApplicationIdle但在我的WPF发展我从未有过的DispatcherPriority微调使用到这种程度。