C#跨线程操作无效 [英] C# Cross-thread operation not valid
问题描述
可能重复:结果
的跨线程操作无效:从不是线程以外的线程访问控制上创建它的
块引用>
我得到一个错误信息 - 任何人都可以给我一些指点。
跨线程操作无效:控制'pbx_1从比它创建的线程以外的
线程访问
块引用>
我已经对这里看看,但我似乎无法得到它的工作。我很新的C#,所以我可能失去了一些东西。
Console.WriteLine(backgroundWorker1);
而(backgroundWorker1.CancellationPending!){
Thread.sleep代码(100);
如果(pbx_1.Location.X< Click_X){
pbx_1.Location =新的点(20,pbx_1.Location.X + MoveAmt);
}
如果(pbx_1.Location.X> Click_X){
pbx_1.Location =新的点(20,pbx_1.Location.X - MoveAmt);
}
backgroundWorker1.ReportProgress(1);
}
解决方案您应该调用
backgroundWorker1.ReportProgress(1);
,因为只有UI线程可以直接访问UI控件。调用示例:私人委托无效AddListBoxItemDelegate(对象的项目);
私人无效AddListBoxItem(对象的项目)
{
如果(this.listBox1.InvokeRequired)
{
//这是一个工作线程,以便委托任务。
this.listBox1.Invoke(新AddListBoxItemDelegate(this.AddListBoxItem)项);
}
,否则
{
//这是UI线程,以便执行任务。
this.listBox1.Items.Add(项目);
}
}
Possible Duplicate:
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on.I get an error message - can anyone give me some pointers.
Cross-thread operation not valid: Control 'pbx_1' accessed from a thread other than the thread it was created on.
I have had a look on here but i cant seem to get it to work. I am quite new to c# so I am probably missing something.
Console.WriteLine("backgroundWorker1"); while (!backgroundWorker1.CancellationPending) { Thread.Sleep(100); if (pbx_1.Location.X < Click_X) { pbx_1.Location = new Point(20, pbx_1.Location.X + MoveAmt); } if (pbx_1.Location.X > Click_X) { pbx_1.Location = new Point(20, pbx_1.Location.X - MoveAmt); } backgroundWorker1.ReportProgress(1); }
解决方案You should Invoke
backgroundWorker1.ReportProgress(1);
, because only UI thread can directly access UI controls. Example of invoking:private delegate void AddListBoxItemDelegate(object item); private void AddListBoxItem(object item) { if (this.listBox1.InvokeRequired) { // This is a worker thread so delegate the task. this.listBox1.Invoke(new AddListBoxItemDelegate(this.AddListBoxItem), item); } else { // This is the UI thread so perform the task. this.listBox1.Items.Add(item); } }
这篇关于C#跨线程操作无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!