c# - 检测是否在 WPF 和 Winforms 的 UI 线程上

标签 c# wpf winforms assertions

我在下面编写了一个断言方法 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/

相关文章:

c# - 如何多次写入一个文件

wpf - 使用 Windows.Forms.Cursor 作为 WPF 光标?

c# - 以编程方式从 JSON 数据生成 JSON 模式

c# - 将多个监听器绑定(bind)到同一个端口

c# - 如何覆盖 App.cs 中的 OnFileActivated 事件以使 OpenWith 正常工作

c# - 使用计时器/任务/后台 worker 的数据采集循环

c# - 如何使用 Xaml 和绑定(bind)自动滚动到 ScrollViewer 的底部?

c# - 如何将 MinorGrid 行数固定为 Microsoft .NET 4.0 Chart 中的固定数字?

c# - 具有依赖注入(inject)的 WinForms MVC

Winforms - 调整窗口大小,但只允许更改高度