简体   繁体   中英

c# WPF InvalidOperationException was unhandled

I have a error when opening a window and closing another.

The calling thread must be STA, because many UI components require this.

I am using RedCorona Sockets... http://www.redcorona.com/Sockets.cs Here is the code...

public partial class MainWindowThingy : Window
{
   public ClientInfo client;
    public MainWindowThingy() //The Error appears here
    {
        InitializeComponent();
        StartTCP();
    }
    public void StartTCP()
    {
        Socket sock = Sockets.CreateTCPSocket("localhost", 2345);
        client = new ClientInfo(sock, false); // Don't start receiving yet
        client.OnReadBytes += new ConnectionReadBytes(ReadData);
        client.BeginReceive();
    }
    void ReadData(ClientInfo ci, byte[] data, int len)
    {
        string msg = (System.Text.Encoding.UTF8.GetString(data, 0, len));
        string[] amsg = msg.Split(' ');
        switch (amsg[0])
        {
            case "login":
                if (bool.Parse(amsg[1]) == true)
                {
                    MainWindowThingy SecondWindow = new MainWindowThingy();
                    Login FirstWindow = new Login();
                    SecondWindow.Show();
                    FirstWindow.Close(); //It starts here, the error...
                }
                else
                {
                }
                break;
        }
    }
}
}

Basicly, It gives me the error at the "Public Control()" When closing The First Form...

Uhm... I want to open another form and close the other... basicly

Edit: Changed Class name...

The callback ReadData is probably being called in a background thread which does not have access to the UI thread. You will need to use Dispatcher.BeginInvoke (explained here ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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