C#/异步网络和GUI之间的通信

标签 c# .net winforms multithreading parallel-processing

我在 C#.NET 中使用 TcpClientTcpListener 类进行异步网络。 我使用 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/

相关文章:

c# - 坚持泛型和接口(interface)。需要基于代码的解决方案,可能需要重新设计接口(interface)

c# - 为标签系统设计数据库的最有效方法

.net - 在没有 Visual Studio 2010 的 Build Machine 中通过 MSbuild 发布

C# Asp.Net MVC - 合并选择列表?

c# - 如何在 Xamarin iOS 中绘制文本?

c# - 如何显示 PI tagsearch 对话框并将标记名作为字符串返回?

c# - 从 Form2 中的类中获取属性的值,并且该值已在 C# 中的 Form1 中设置

c# - mdi 子窗体最大化窗口状态 - BorderStyle

c# - 反序列化hal+json为复杂模型

c# - 如何使用 C# 淡入/淡出包含内容的面板