#region 解决线程间操作无效: 从不是创建控件“label1”的线程访问它问题
delegate void SetTextCallback(string a);//先创建一个委托
/// <summary>
/// 线程间操作无效: 从不是创建控件“label1”的线程访问它
/// </summary>
/// <param name="text">需要赋值给控件的值</param>
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the 线程ID进行比较
// calling thread to the thread ID of the creating thread.调用线程到创建线程的线程ID。
// If these threads are different, it returns true.如果这些线程不同,则返回true。
////防止跨线程访问控件
if (this.label1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
//this.label1.Invoke(new Action(()=>{this.label1.Text = text;}))
}
else
{
this.label1.Text = text;
}
//同上
// Invoke(new MethodInvoker(delegate()
// {
// this.label1.Text = text;
// }));
//异步线程操作
//this.BeginInvoke(new Action(() =>
// {
// ConstructTreeDoorUnionVideo();
// }));
}
#endregion
MethodInvoker threadValue = new MethodInvoker(ThdFunc);
threadValue.BeginInvoke(null, null);
private void ThdFunc()
{
//获取数据
//显示数据
}
public void PlayVideoNum(List<int> lstVp)
{
if (InvokeRequired)
{
BeginInvoke(new Action(() => PlayVideoNum(lstVp)));
}
}
//作用 加快界面加载
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= 0x02000000;
return cp;
}
}
线程间操作无效: 从不是创建控件“label1”的线程访问它。
于 2019-08-07 11:24:55 首次发布
本文介绍了在编程中遇到的线程间操作无效错误,特别是当尝试从非创建线程访问GUI控件如'Label1'时。文章将探讨这个问题的原因,并提供解决方案,包括使用Invoke或BeginInvoke方法来防止跨线程访问控件。
开发板推荐:天空星STM32F407VET6开发板
超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印
开发板推荐:天空星STM32F407VET6开发板
超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印


522

被折叠的 条评论
为什么被折叠?



