[转]C#中Invoke的用法

本文介绍了一个使用TcpClient.BeginConnect实现异步TCP连接的DEMO,并通过委托方式安全地更新WinForm控件显示状态的过程。解决了跨线程访问WinForm控件的问题。
在做一个测试Tcp连接的DEMO,想用TcpClient.BeginConnect异步调用,在回调方法里更新winform.TextBox的值输出结果,直接使用TextBox.Text出错(线程间操作无效,不是从创建控件XX的线程访问他),想过使用winform.Invoke不过一直想Inovke将Tcp连接进行封装委托,原来应该将更新界面的方法进行委托。
最后代码
public partial class MainForm : Form
    {
        private string _serverAddress = string.Empty;
        private int _port = 80;
        delegate void SetTextCallback(string text);
        public MainForm()
        {
            InitializeComponent();
        }
        private void connectButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.serverAddressTextBox.Text))
            {
                this.tipsTextBox.Text = "请输入服务器IP地址\r\n";
            }
            if (string.IsNullOrEmpty(this.portTextBox.Text))
            {
                this.tipsTextBox.Text="请输入端口号\r\n";
            }
            else
            {
                _serverAddress = this.serverAddressTextBox.Text;//连接IP地址
                _port = Convert.ToInt32(this.portTextBox.Text);//端口号
               
                this.tipsTextBox.Text = this.tipsTextBox.Text + "开始建立连接.....\r\n";
                this.tipsTextBox.Text = this.tipsTextBox.Text + "请等待.....\r\n";
                TcpClient tcpClient = new TcpClient();
                //开启异步TCP连接
                IAsyncResult asr=tcpClient.BeginConnect(_serverAddress, _port, new AsyncCallback(RequestCallBack), tcpClient);
                //try
                //{
                //    tcpClient.EndConnect(asr);
                //}
                //catch (System.Exception ex)
                //{
                //    this.tipsTextBox.Text = this.tipsTextBox.Text + "错误:" + ex.Message + "\r\n";
                //}
                //finally
                //{
                //    this.tipsTextBox.Text = this.tipsTextBox.Text + "操作是否完成:" + asr.IsCompleted + "\r\n";
                //    this.tipsTextBox.Text = this.tipsTextBox.Text + "连接结果:" + ((TcpClient)asr.AsyncState).Connected + "\r\n"; 
       
### 使用 在C#,`Invoke`方法主要用于在UI线程上执行代码。在Windows Forms和WPF应用程序,由于UI控件不是线程安全的,只能在创建它们的线程(通常是主线程,即UI线程)上访问和修改。当需要从其他线程更新UI时,就需要使用`Invoke`方法。 ### 原理 `Invoke`方法的原理是将一个委托(通常是一个方法)排队到UI线程的消息队列。当UI线程处理到这个消息时,会执行该委托所代表的方法。这样就保证了对UI控件的访问是在UI线程上进行的,避免了线程安全问题。 ### 示例 以下是一个Windows Forms应用程序使用`Invoke`方法的示例: ```csharp using System; using System.Threading; using System.Windows.Forms; namespace InvokeExample { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 启动一个新线程来模拟耗时操作 Thread workerThread = new Thread(DoWork); workerThread.Start(); } private void DoWork() { // 模拟耗时操作 Thread.Sleep(2000); // 在UI线程上更新UI控件 if (this.InvokeRequired) { this.Invoke(new Action(() => { label1.Text = "操作完成"; })); } else { label1.Text = "操作完成"; } } } } ``` 在这个示例,当用户点击按钮时,会启动一个新线程来执行`DoWork`方法。在`DoWork`方法,首先模拟了一个耗时操作,然后检查是否需要使用`Invoke`方法来更新`label1`的文本。如果需要,则使用`Invoke`方法将更新操作排队到UI线程的消息队列
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值