Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine what is blocking UI thread

I am working on a rather large .NET WPF real-time application. The application is working great and as expected, except for one BIG issue - UI Update is slow.

This application is highly event driven, there are events raised all over for all sorts of things - through these events the UI is updated.

One or many of these events is blocking the UI from displaying immediately. When all the work is complete, the UI shows the expected results.

Is there any way of determining which event handler is causing the bottleneck?

like image 407
c0D3l0g1c Avatar asked Sep 21 '10 09:09

c0D3l0g1c


2 Answers

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

    }

}

Just new this class in MainWindow constructor. When the breakpoint hits, you can go to Visual Studio --> Debug --> Windows --> Threads and check what operation blocked your UI-Thread!

like image 121
Andreas Avatar answered Oct 12 '22 19:10

Andreas


I fully support colithium's suggestion of using a profiler.

In addition, if the blocking takes more than a second, you might be able to hit the "Pause" button in Visual Studio. In the tool bar, there's a dropdown list where you can choose the "Main Thread". Then it jumps to the method which is currently blocking the UI.

like image 44
Heinzi Avatar answered Oct 12 '22 21:10

Heinzi