异步联网和GUI的C#/通讯 [英] C# / Communication between Async networking and GUI

查看:95
本文介绍了异步联网和GUI的C#/通讯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做异步网络中的C#.NET与的TcpClient 的TcpListener 类。 我使用的WinForms的GUI。

I'm doing async network in C#.NET with the TcpClient and TcpListener classes. I use WinForms for the GUI.

每当我收到的数据从远程计算机的操作做了不同的底层线程。

Whenever I receive data from a remote computer, the operation is done on a different underlying thread.

我需要做的是,每当我收到一个网络的响应来更新我的应用程序的GUI。

What I need to do is to update the GUI of my application whenever I receive a network response.

// 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)
}

我怎样才能做到这一点?

How can I achieve that?

推荐答案

在的WinForms,你需要使用的 Control.Invoke方法(代表),以确保控制在UI线程更新。

In Winforms you need to use Control.Invoke Method (Delegate) to make sure that control is updated in the UI thread.

例如:

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

用法:

PerformInvoke(textBox1, () => { textBox1.Text = "test"; });

这篇关于异步联网和GUI的C#/通讯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆