[转]C#中Invoke的用法

在做一个测试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"; 
       
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值