c#WPF InvalidOperationException未处理

时间:2014-02-08 17:36:23

标签: c# wpf sockets mahapps.metro

打开一个窗口并关闭另一个窗口时出错。

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

我正在使用RedCorona套接字...... http://www.redcorona.com/Sockets.cs 这是代码......

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

基本上,它给了我“公共控制()”的错误 关闭第一张表格时......

嗯......我想打开另一张表格并关闭另一张......基本上

编辑: 更改了班级名称......

1 个答案:

答案 0 :(得分:2)

回调ReadData可能是在后台线程中调用的,后台线程无权访问UI线程。您需要使用Dispatcher.BeginInvoke(解释here)。