C#中Invoke的用法

时间:2022-08-28 07:30:08
在做一个测试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";