public Object lock_scan = new Object();//锁
public void Execute(string device,int n_cpk)
{
object[] paras = new object[] { device,n_cpk};
new Thread(new ParameterizedThreadStart(tExecuteLoop)).Start(paras);
}
private void tExecuteLoop(object para)
{
object[] paras = (object[])para;
string device = (string)paras[0];
int n_cpk=(int)paras[1];
//doing...
label_CPKText(n_cpk.ToString());//线程中使用回调函数 操作界面控件
lock (lock_scan)//需要上锁的操作 可以放到这里
{
}
}
/// <summary>
/// 回调函数 线程中输出到界面控件
/// </summary>
/// <param name="text"></param>
delegate void label_CPKTextCallback(string text);
private void label_CPKText(string text)
{
// 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.label_CPK.InvokeRequired)//如果调用控件的线程和创建创建控件的线程不是同一个则为True
{
while (!this.label_CPK.IsHandleCreated)
{
//解决窗体关闭时出现“访问已释放句柄“的异常
if (this.label_CPK.Disposing || this.label_CPK.IsDisposed){return;}
}
label_CPKTextCallback d = new label_CPKTextCallback(label_CPKText);
this.label_CPK.Invoke(d, new object[] { text });
}
else
{
this.label_CPK.Text = text;
}
}
C# 线程传参 回调函数更新界面控件 互斥区域上锁
最新推荐文章于 2022-04-06 20:00:39 发布