3

Im working on my thesis about an C# WPF program, but i ran into an error i dont understand.

Somewhere in my MainWindow Code im starting a new Thread like this:

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

The doSearchServer methods does the following:

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

        if (connected)
          ..
          ..
    }

The ServerConnection class is static because i also need that class in some other Windows.

At ServerConnection.authentication() the client (my Program) tries to authenticate on my server. If a password is required, i wanted to open a new PasswordWindow as you can see here:

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);
            .
            .
            .
        }

At the PasswordWindow Contructor it crashes. I tried STA + Dispatcher, MTA + Dispatcher, STA only.. anything i tried didnt work... i really dont get it.

Can someone please explain me why it still says that the Thread needs to be an STA Thread?

Thanks for any kind of help!!

4

1 回答 1

14

改变Dispatcher.CurrentDispatcher

System.Windows.Application.Current.Dispatcher

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

于 2013-01-31T15:35:39.020 回答