线程必须是STA线程,但它已经是了。

3
我是一个有用的助手,可以为您翻译文本。
我正在撰写一篇关于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等方法,但都没有起作用...我真的不明白。
有人能解释一下为什么它仍然说线程需要是STA线程吗?
感谢任何形式的帮助!
1个回答

14

Dispatcher.CurrentDispatcher改为System.Windows.Application.Current.Dispatcher,因为当从不是“UI线程”(与首次启动应用程序的Dispatcher相关联的线程)访问Dispatcher.CurrentDispatcher属性时,会创建一个新的Dispatcher,这不是你此处所需的。


从来没有发现那个错误...即使是我的编程老师也没有发现它。非常感谢 :-) - Maaaario
天哪,你有一位编程老师,而且他正在教你WPF?你真幸运! - Federico Berasategui
是的,我们有 :-) 他还教了我们一些C++游戏编程,但大多数时间我们在做WPF :) - Maaaario
@Bobb 不,我不是在讽刺。WPF 是最令人愉悦的框架之一。与之一起工作是愉快和直接的,相比之下,在 WinForms 中几乎需要进行多次 HACK 才能做任何有用的事情。更不用说 .Net 世界之外的其他事情,比如 Java,它甚至没有真正的泛型、委托或 LinQ。 - Federico Berasategui

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接