2011-06-12 62 views
1

我在C#.NET中使用TcpClientTcpListener類進行異步網絡。 我使用GUI的WinForms。C#/異步網絡和GUI之間的通信

每當我從遠程計算機收到數據時,操作都是在不同的基礎線程上完成的。

我需要做的是每當我收到網絡響應時更新我的​​應用程序的GUI。

// this method is called whenever data is received 
// it's async so it runs on a different thread 
private void OnRead(IAsyncResult result) 
{ 
    // update the GUI here, which runs on the main thread 
    // (a direct modification of the GUI would throw a cross-thread GUI exception) 
} 

我該如何做到這一點?

回答

3

在Winforms中,您需要使用Control.Invoke Method (Delegate)來確保控件在UI線程中更新。

例子:

public static void PerformInvoke(Control ctrl, Action action) 
{ 
    if (ctrl.InvokeRequired) 
     ctrl.Invoke(action); 
    else 
     action(); 
} 

用法:

在GUI
PerformInvoke(textBox1,() => { textBox1.Text = "test"; }); 
+0

重複使用,非常整齊。非常感謝先生! – asmo 2011-06-12 02:09:30

2

寫這樣的功能:

public void f() { 

     MethodInvoker method =() => { 
      // body your function 
     }; 

     if (InvokeRequired) { 
      Invoke(method); // or BeginInvoke(method) if you want to do this asynchrous 
     } else { 
      method(); 
     } 
    } 

,如果你在其他線程調用該函數將在GUI調用線程

0

我向Alex建議的代碼添加了擴展方法。它變得更好!

// Extension method 
public static class GuiHelpers 
{ 
    public static void PerformInvoke(this Control control, Action action) 
    { 
     if (control.InvokeRequired) 
      control.Invoke(action); 
     else 
      action(); 
    } 
} 


// Example of usage 
private void EnableControls() 
{ 
    panelMain.PerformInvoke(delegate { panelMain.Enabled = true; }); 
    linkRegister.PerformInvoke(delegate { linkRegister.Visible = true; }); 
}