2015-11-13 131 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微調使用到這種程度。