2014-02-08 88 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()); –

相關問題