Dot-Net

確定是什麼阻塞了 UI 執行緒

  • October 27, 2020

我正在開發一個相當大的 .NET WPF 實時應用程序。該應用程序執行良好且符合預期,除了一個大問題 - UI 更新很慢。

這個應用程序是高度事件驅動的,有各種各樣的事件引發 - 通過這些事件更新 UI。

這些事件中的一個或多個會阻止 UI 立即顯示。完成所有工作後,UI 會顯示預期結果。

有沒有辦法確定哪個事件處理程序導致了瓶頸?

我完全支持 colithium 關於使用分析器的建議。

此外,如果阻塞時間超過一秒,您可以點擊 Visual Studio 中的“暫停”按鈕。在工具欄中,有一個下拉列表,您可以在其中選擇“主執行緒”。然後它跳轉到目前阻塞 UI 的方法。

 public class UIBlockDetector
{
   static Timer _timer;
   public UIBlockDetector(int  maxFreezeTimeInMilliseconds = 200)
   {
       var sw = new Stopwatch();

       new DispatcherTimer(TimeSpan.FromMilliseconds(10), DispatcherPriority.Send, (sender, args) =>
       {
           lock (sw)
           {
               sw.Restart();
           }

       }, Application.Current.Dispatcher);

       _timer = new Timer(state =>
       {
           lock (sw)
           {
               if (sw.ElapsedMilliseconds > maxFreezeTimeInMilliseconds)
               {
                   // Debugger.Break() or set breakpoint here;
                   // Goto Visual Studio --> Debug --> Windows --> Theads 
                   // and checkup where the MainThread is.
               }
           }

       }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromMilliseconds(10));

   }

}

只是在 MainWindow 建構子中新建這個類。當斷點命中時,您可以轉到 Visual Studio –> Debug –> Windows –> Threads 並檢查哪些操作阻塞了您的 UI-Thread!

引用自:https://stackoverflow.com/questions/3758838