我在 C#.NET 中使用 TcpClient
和 TcpListener
类进行异步网络。
我使用 WinForms 作为 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)
}
我怎样才能做到这一点?
最佳答案
在 Winforms 中你需要使用 Control.Invoke Method (Delegate)以确保控件在 UI 线程中更新。
例子:
public static void PerformInvoke(Control ctrl, Action action)
{
if (ctrl.InvokeRequired)
ctrl.Invoke(action);
else
action();
}
用法:
PerformInvoke(textBox1, () => { textBox1.Text = "test"; });
关于C#/异步网络和GUI之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6319509/