c# - 线程必须是 STA-Thread,但它已经是

标签 c# wpf multithreading dispatcher sta

我正在写关于 C# WPF 程序的论文,但我遇到了一个我不明白的错误。

在我的 MainWindow 代码中的某处,我开始了一个新线程,如下所示:

Thread searchServer = new Thread(new ThreadStart(doSearchServer));
            searchServer.SetApartmentState(ApartmentState.STA);
            searchServer.Start();

doSearchServer 方法执行以下操作:

    private void doSearchServer()
    {
        bool connected = ServerConnection.authentication();
        ServerConnection.getDeviceList();
        gotDataFromServer = connected;

        if (connected)
          ..
          ..
    }

ServerConnection 类是静态的,因为我在其他一些 Windows 中也需要该类。

在 ServerConnection.authentication() 中,客户端(我的程序)尝试在我的服务器上进行身份验证。如果需要密码,我想打开一个新的 PasswordWindow,如您所见:

public static bool authentication()
    {
        UdpClient client = new UdpClient();
        IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 55042);
        IPEndPoint ipRec = new IPEndPoint(IPAddress.Any, 0);

        byte[] bytes = Encoding.UTF8.GetBytes("authent|Username|Windows");
        client.Send(bytes, bytes.Length, ip);

        //Receive Answer
        byte[] recBuffer = client.Receive(ref ipRec);
        string recString = Encoding.UTF8.GetString(recBuffer);

        if (recString.Equals("authent|password"))
        {
            //Send Passwort
            Console.WriteLine("Password Required");

            Dispatcher.CurrentDispatcher.Invoke(new Action(() =>
            {
            PasswordWindow pw = new PasswordWindow();
            pw.ShowDialog();
            if (pw.ShowDialog() == true)
            {
                //send PW
            }
            else
            {
                //Dont send PW
            }
            }));

            client.Send(bytes, bytes.Length, ip);
            .
            .
            .
        }

在 PasswordWindow 构造函数中它崩溃了。我尝试了 STA + Dispatcher、MTA + Dispatcher、STA only..我试过的任何东西都不起作用......我真的不明白。

谁能解释一下为什么它仍然说线程需要是 STA 线程?

感谢您的帮助!!

最佳答案

更改 Dispatcher.CurrentDispatcher

System.Windows.Application.Current.Dispatcher

因为当从不是“UI 线程”的线程访问 Dispatcher.CurrentDispatcher 属性时(与第一个启动应用程序的 Dispatcher 关联的线程) place),一个新的 Dispatcher 被创建,这不是你在这里需要的。

关于c# - 线程必须是 STA-Thread,但它已经是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14629298/

相关文章:

c# - 多列 TreeView

c# - 为什么我的 google 帐户验证失败?

c# - 是否有 C# 等效于 Java 的 BlockingQueue.drainTo(Collection) 方法?

c# - 如何重置 PipeReader 以便能够在 ASP.NET Core 中重新读取请求正文

c# - 在服务器上执行 powershell .ps1 文件并查看结果 C# asp.net

c# - WPF MediaElement 应用的播放列表

请提供 C++ 线程和字符串帮助

java - 新线程 JDialog 中的 JProgressBar

wpf - 是否有可用的 WPF "WrapGrid"控件或创建控件的简单方法?

wpf - Caliburn Micro 中的 Bootstrap