我在下面编写了一个断言方法 Ensure.CurrentlyOnUiThread(),用于检查当前线程是否为 UI 线程。
- 这在检测 Winforms UI 线程时是否可靠?
- 我们的应用混合了 WPF 和 Winforms,如何最好地检测有效的 WPF UI 线程?
- 有更好的方法吗?也许代码契约(Contract)?
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 dispatcher = Dispatcher.FromThread(Thread.CurrentThread);
if (dispatcher != null)
{
// We know the thread have a dispatcher that we can use.
}
为确保您有正确的调度程序或在正确的线程上,您有以下选项
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()
不会出现在智能感知中。
此外,如果您不得不求助于这些类型的东西,则可能是由于设计不当。您应该知道哪些线程在您的程序中运行哪些代码。
关于c# - 检测是否在 WPF 和 Winforms 的 UI 线程上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5143599/