Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying the Dispatcher Queue Length

Tags:

wpf

I'm trying to analyse the usage of the UI thread. Is it possible to query the number of items queued by the dispatcher?

UPDATE: Clemens answer works perfectly, however as I want to kick this off after the UI has started and I only care to sample the data once per second I use the following code...

        int queueLength = 0;
        var currentDispatcher = Dispatcher.CurrentDispatcher;
        currentDispatcher.Hooks.OperationPosted += (s, e) => Interlocked.Increment(ref queueLength);
        currentDispatcher.Hooks.OperationCompleted += (s, e) => Interlocked.Decrement(ref queueLength);
        currentDispatcher.Hooks.OperationAborted += (s, e) => Interlocked.Decrement(ref queueLength);
        Observable
            .Interval(TimeSpan.FromSeconds(1))
            .Subscribe(x =>
                           {
                               int currentQueueLength = queueLength;
                               if (currentQueueLength < 0)
                               {
                                   Interlocked.Add(ref queueLength, currentQueueLength * -1);
                               }
                               UiQueueLength = queueLength;
                           });
like image 806
Noob Avatar asked Jan 10 '13 15:01

Noob


1 Answers

Afaik there is no property or method where you can directly ask for the dispatcher queue length. You may however attach handlers to some of the DispatcherHooks events, provided by the Hooks property.

var queueLength = 0;
Dispatcher.Hooks.OperationPosted += (o, e) => Interlocked.Increment(ref queueLength);
Dispatcher.Hooks.OperationStarted += (o, e) => Interlocked.Decrement(ref queueLength);
Dispatcher.Hooks.OperationAborted += (o, e) => Interlocked.Decrement(ref queueLength);

If you are only interested in whether the Dispatcher is active or not, you might just handle the OperationPosted event in conjunction with DispatcherInactive.

like image 181
Clemens Avatar answered Sep 29 '22 13:09

Clemens