如何检测 Dispatcher.DisableProcessing 是否处于活动状态?

发布于 2024-08-08 11:57:50 字数 1003 浏览 4 评论 0原文

如果在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

轮廓§ 2024-08-15 11:57:50

那里没有公共界面,因此您没有合法的方式来判断它是否被暂停。您仍然可以使用反射,但一般来说,这表明您正在做一些完全错误的事情。

如果您能给我们更多详细信息,我们可以建议适当的解决方案吗?

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?

┼── 2024-08-15 11:57:50

试试这个:

if(currentDispatcher.Thread.ThreadState == System.Threading.ThreadState.Suspended)
{

}

try this:

if(currentDispatcher.Thread.ThreadState == System.Threading.ThreadState.Suspended)
{

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文