2014-02-08 50 views
-1

打开窗口并关闭另一个窗口时出现错误。c#WPF InvalidOperationException未处理

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

基本上,它给我的错误,在 “公共控制()” 当关闭第一种形式......

呃... ...我想开另一种形式,并关闭其他... basicly

编辑: 更改类名称...

+0

你是从后台线程调用它吗? –

+0

不要将您的窗口命名为“Control”。这已经是.NET Framework中的一个类,只会在后续阶段产生问题。 – nvoigt

+0

我这么认为......但我不知道如何使用dispacher在这... 你能举个例子吗? – user2993512

回答

2

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

+0

你能举个例子吗? – user2993512

+0

您是否阅读过我提供的链接?首先在调用StartTCP();之前获取对FirstWindow.Dispatcher的引用。之后调用Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.SystemIdle,()=> FirstWindow.Close()); –