我正在尝试分析UI线程的使用情况。是否可以查询分派器排队的项目数量?
更新:Clemens的答案完美地解决了问题,但我想在UI启动后启动它,并且我只关心每秒采样一次数据,因此我使用以下代码...
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;
});