c#中如何跨线程调用windows控件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#中如何跨线程调用windows控件相关的知识,希望对你有一定的参考价值。
参考技术A 在辅助线程调用(在创建辅助线程时可将此方法通过delegate传到辅助线程中)下面的方法InvokeControl();//写在主线程中(windows控件)
private void InvokeControl()
if (this.InvokeRequired)
this.Invoke(new DelegateChangeText(ChangeText));
else
this.ChangeText();
private void ChangeText()
this.TextBox.Text = "sd";
public delegate void DelegateChangeText(); 参考技术B 定义委托,然后用invoke
private
void
ucMidPartsid_Load(object
sender,
EventArgs
e)
if
(is_Load
==
true)
thread
=
new
Thread(new
ThreadStart(this.LoadData));
thread.Start();
//if
(datafinish
!=
null)
//
//
datafinish(this,
e);
//
private
void
LoadData()
QueryDataCallBack
deleg;
deleg
=
new
QueryDataCallBack(this.DataBinding);
this.Invoke(deleg,null);
private
void
DataBinding()
partstableAdapter
=
new
GreatWall.SCM.Parts.DataAccess.DAParts.PartsTableAdapter();
partstableAdapter.Fill(dsParts.GB_PARTS);
cobMidPartsid.DataSource
=
dsParts.GB_PARTS;
cobMidPartsid.DisplayMember
=
"B_PARTSID";
cobMidPartsid.ValueMember
=
"B_ID";
EventArgs
e
=
new
EventArgs();
if
(datafinish
!=
null)
finish
=
true;
datafinish(this,
e);
参考技术C 在构造函数里使用属性
CheckForIllegalCrossThreadCalls 值设置为 false
即 public Form1()
CheckForIllegalCrossThreadCalls = false;
参考技术D 定义委托,然后用invoke
private void ucMidPartsid_Load(object sender, EventArgs e)
if (is_Load == true)
thread = new Thread(new ThreadStart(this.LoadData));
thread.Start();
//if (datafinish != null)
//
// datafinish(this, e);
//
private void LoadData()
QueryDataCallBack deleg;
deleg = new QueryDataCallBack(this.DataBinding);
this.Invoke(deleg,null);
private void DataBinding()
partstableAdapter = new GreatWall.SCM.Parts.DataAccess.DAParts.PartsTableAdapter();
partstableAdapter.Fill(dsParts.GB_PARTS);
cobMidPartsid.DataSource = dsParts.GB_PARTS;
cobMidPartsid.DisplayMember = "B_PARTSID";
cobMidPartsid.ValueMember = "B_ID";
EventArgs e = new EventArgs();
if (datafinish != null)
finish = true;
datafinish(this, e);
本回答被提问者采纳 第5个回答 2007-12-19 定义委托 delegate
调用 Invoke
提问之前先利用baidu搜索下吧
以上是关于c#中如何跨线程调用windows控件的主要内容,如果未能解决你的问题,请参考以下文章
C# Winform项目中多线程环境下, 如何跨线程对Window窗体控件进行安全访问?