3
votes

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!!

1

1 Answers

14
votes

change Dispatcher.CurrentDispatcher

to

System.Windows.Application.Current.Dispatcher

because when accessing the Dispatcher.CurrentDispatcher property from a thread that is not the "UI Thread" (the one associated with the Dispatcher that started the application in the first place), a new Dispatcher is created, which is not what you need here.