检测是否在 WPF 和 Winforms 中的 UI 线程上 [英] Detecting whether on UI thread in WPF and Winforms
问题描述
我在下面编写了一个断言方法 Ensure.CurrentlyOnUiThread(),用于检查当前线程是否为 UI 线程.
I've written an assertion method Ensure.CurrentlyOnUiThread(), below, that checks that the current thread is a UI thread.
- 这在检测 Winforms UI 线程时是否可靠?
- 我们的应用混合了 WPF 和 Winform,如何最好地检测有效的 WPF UI 线程?
- 有没有更好的方法来做到这一点?也许代码契约?
Ensure.cs
using System.Diagnostics;
using System.Windows.Forms;
public static class Ensure
{
[Conditional("DEBUG")]
public static void CurrentlyOnUiThread()
{
if (!Application.MessageLoop)
{
throw new ThreadStateException("Assertion failed: not on the UI thread");
}
}
}
推荐答案
请勿使用
if(Dispatcher.CurrentDispatcher.Thread == Thread.CurrentThread)
{
// Do something
}
Dispatcher.CurrentDispatcher
将,如果当前线程没有调度器,则创建并返回一个与当前线程关联的新 Dispatcher
.
Dispatcher.CurrentDispatcher
will, if the current thread do not have a dispatcher, create and return a new Dispatcher
associated with the current thread.
改为这样做
Dispatcher dispatcher = Dispatcher.FromThread(Thread.CurrentThread);
if (dispatcher != null)
{
// We know the thread have a dispatcher that we can use.
}
为了确保您有正确的调度员或在正确的线程上,您有以下选项
To be sure you have the correct dispatcher or are on the correct thread you have the following options
Dispatcher _myDispatcher;
public void UnknownThreadCalling()
{
if (_myDispatcher.CheckAccess())
{
// Calling thread is associated with the Dispatcher
}
try
{
_myDispatcher.VerifyAccess();
// Calling thread is associated with the Dispatcher
}
catch (InvalidOperationException)
{
// Thread can't use dispatcher
}
}
CheckAccess()
和 VerifyAccess()
没有出现在智能感知中.
CheckAccess()
and VerifyAccess()
do not show up in intellisense.
此外,如果您不得不求助于这些类型的东西,很可能是由于设计不当.您应该知道哪些线程在您的程序中运行哪些代码.
Also, if you have to resort to these kinds of things its likely due to bad design. You should know which threads run what code in your program.
这篇关于检测是否在 WPF 和 Winforms 中的 UI 线程上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!