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;
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With