Determine what is blocking UI thread Determine what is blocking UI thread multithreading multithreading

Determine what is blocking UI thread


  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!


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.


Do you have access to a code profiler? This is the type of thing they are good at. I recommend obtaining one if the answer is no.

Besides using a profiler. You can do "poor man's" profiling by placing timing statements at the beginning and end of code blocks that you suspect. You can even use a breakpoints and time it with a wall clock. Does the issue happen when you click something? If so start there. Is it a recurring issue without user interaction? Start with timers then.

As for actually solving the problem... Unless the offending handler is doing something that can be made more efficient, consider adopting a multi-threaded approach. The new Task library for .NET 4.0 is really amazing in this regard.