如何检测 Dispatcher.DisableProcessing 是否处于活动状态?
如果在 Dispatcher
挂起(调用 Dispatcher.DisableProcessing()
)的情况下尝试显示消息框,则会引发异常。
InvalidOperationException:“调度程序处理已暂停”(请参阅此处)。
有谁知道我如何检测 Dispatcher
是否被挂起(这样我就知道何时调用 BeginInvoke()
)?
编辑1:
为了响应Application.DispatcherUnhandledException事件,我试图显示一个MessageBox。但是,如果在 DataBinding 期间引发此未处理的异常(即 ItemsControl.ItemsSource
),则 Dispatcher
将挂起。尝试显示 MessageBox
然后失败。始终使用 Dispatcher.BeginInvoke() 可以解决问题,但除非确实有必要,否则我不想这样做。
编辑 2:
使用反射来完成此工作,如下所示:
var dispatcherType = typeof(Dispatcher);
var countField = dispatcherType.GetField("_disableProcessingCount", BindingFlags.Instance | BindingFlags.NonPublic);
var count = (int)countField.GetValue(Dispatcher.CurrentDispatcher);
var suspended = count > 0;
An exception is raised if one tries to show a message box if the Dispatcher
is suspended (Dispatcher.DisableProcessing()
called).
InvalidOperationException: 'Dispatcher processing has been suspended' (see here).
Does anyone know how I can detect where the Dispatcher
is suspended or not (so I know when to call BeginInvoke()
)?
Edit 1:
In reaction to the Application.DispatcherUnhandledException event I'm trying to show a MessageBox. However, if this unhandled Exception was thrown during DataBinding (i.e. ItemsControl.ItemsSource
) the Dispatcher
is suspended. Trying to show a MessageBox
then fails. Always using Dispatcher.BeginInvoke()
solves the problem, but I don't want to do that unless really necessary.
Edit 2:
Using Reflection to accomplish this works like this:
var dispatcherType = typeof(Dispatcher);
var countField = dispatcherType.GetField("_disableProcessingCount", BindingFlags.Instance | BindingFlags.NonPublic);
var count = (int)countField.GetValue(Dispatcher.CurrentDispatcher);
var suspended = count > 0;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那里没有公共界面,因此您没有合法的方式来判断它是否被暂停。您仍然可以使用反射,但一般来说,这表明您正在做一些完全错误的事情。
如果您能给我们更多详细信息,我们可以建议适当的解决方案吗?
There is no public interface there so you don't have a legal way to say whether it's suspended or not. You still can use reflection, but generally speaking this indicates you are doing something totally wrong.
If you could give us more details we could suggest proper solution?
试试这个:
try this: