C#多线程访问Winform控件方法总结
(2018-01-22 15:04:11)
标签:
it |
分类: JAVA/C#/Cpp/C语言/Python |
参考博文:C#中使用多线程访问Winform中控件的若干问题
txtRead.AppendText(text.ToString("X2"));
txtRead.AppendText(" ");
// richtextbox滚动条自动移至最后一条记录
txtRead.Focus();
//让文本框获取焦点
txtRead.Select(txtRead.TextLength, 0);
//设置光标的位置到文本尾
txtRead.ScrollToCaret();
//滚动到控件光标处
//判断是否是显示为16禁止
if
(checkBoxHexView.Checked)
{
//依次的拼接出16进制字符串
foreach (byte b in buf)
{
builder.Append(b.ToString("X2") + " ");
}
}
else
{
//直接按ASCII规则转换成字符串
builder.Append(Encoding.ASCII.GetString(buf));
}
//追加的形式添加到文本框末端,并滚动到最后。
this.txGet.AppendText(builder.ToString());
//修改接收计数
labelGetCount.Text =
"Get:" + received_count.ToString();
// InvokeRequired
required compares the thread ID of the
// calling thread to the
thread ID of the creating thread.
// If these threads are
different, it returns true.
if
(this.txtReadInt.InvokeRequired)
{
SetTextCallback d = new
SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.txtReadInt.Text = text;
}
根据以上博文汇总,并经过自己实践罗列出以下两种方法:
1、使用invoke方式同步ui:
示例一:
this.Invoke((EventHandler)(delegate
{
}));
示例二:
//因为要访问ui资源,所以需要使用invoke方式同步ui。
this.Invoke((EventHandler)(delegate
{
}));
2.利用SetTextCallback跨线程调用TextBox方法:
详细解析参考博文:C#利用SetTextCallback跨线程调用TextBox方法浅析
示例:
delegate void SetTextCallback(string
text);//安全线程访问txtReadInt控件的值
//线程安全访问txtReadInt控件
private void SetText(string text)
{
}
注意:C#.NET多线程访问toolStripStatusLabel控件比较特殊,无法定义invoke来线程调用。
原以为只好使用原生委托..代码稍微多一些..
其实也可使用this.Invoke
this.Invoke(new EventHandler(delegate
{
}));
前一篇:C#之static的用法详解
后一篇:C#中的is和as操作符