繁体   English   中英

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

[英]Thread must be STA-Thread, but it already is

我正在研究关于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 Contructor它崩溃了。 我尝试过STA + Dispatcher,MTA + Dispatcher,STA ..我试过的任何东西都没有工作......我真的不明白。

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

谢谢你的帮助!!

更改Dispatcher.CurrentDispatcher

System.Windows.Application.Current.Dispatcher

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM