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

Maa*_*rio 3 c# wpf multithreading dispatcher sta

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

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

Thread searchServer = new Thread(new ThreadStart(doSearchServer));
            searchServer.SetApartmentState(ApartmentState.STA);
            searchServer.Start();
Run Code Online (Sandbox Code Playgroud)

doSearchServer方法执行以下操作:

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

        if (connected)
          ..
          ..
    }
Run Code Online (Sandbox Code Playgroud)

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);
            .
            .
            .
        }
Run Code Online (Sandbox Code Playgroud)

在PasswordWindow Contructor它崩溃了.我尝试过STA + Dispatcher,MTA + Dispatcher,STA ..我试过的任何东西都没有工作......我真的不明白.

有人可以解释一下为什么它仍然说线程需要是一个STA线程吗?

谢谢你的帮助!!

Fed*_*gui 13

更改 Dispatcher.CurrentDispatcher

System.Windows.Application.Current.Dispatcher

因为当Dispatcher.CurrentDispatcher从不是"UI线程"的线程(与Dispatcher首先启动应用程序的线程相关联的线程)访问属性时,Dispatcher会创建一个新的,这不是您需要的.