我正在尝试分析UI线程的用法.是否可以查询调度员排队的物品数量?
更新:克莱门斯的答案是完美的,但是因为我想在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;
});
Run Code Online (Sandbox Code Playgroud)
Afaik没有属性或方法可以直接请求调度程序队列长度.但是,您可以将处理程序附加到Hooks属性提供的某些DispatcherHooks事件.
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);
Run Code Online (Sandbox Code Playgroud)
如果你只能在调度员是否是活动的兴趣或没有,你可能只是处理OperationPosted事件会同DispatcherInactive.