查询调度队列长度 [英] Querying the Dispatcher Queue Length

查看:27
本文介绍了查询调度队列长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试分析 UI 线程的使用情况.是否可以查询调度员排队的物品数量?

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

更新:Clemens 的回答完美无缺,但是因为我想在 UI 启动后启动它并且我只关心每秒采样一次数据,所以我使用以下代码...

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 没有任何属性或方法可以直接询问调度程序队列长度.但是,您可以将处理程序附加到某些 DispatcherHooks 事件,由Hooks 属性.

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

<小时>

如果您只对 Dispatcher 是否处于活动状态感兴趣,您可以只处理 OperationPosted 事件与 DispatcherInactive.

这篇关于查询调度队列长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆