C#线程访问其他线程 [英] c# threading access to other thread
本文介绍了C#线程访问其他线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此错误:跨线程操作无效:从创建该线程的线程之外的其他线程访问控件'progressBar1'."我似乎不知道该怎么解决.
I have this error: Cross-thread operation not valid: "Control 'progressBar1' accessed from a thread other than the thread it was created on." I can't seem to figure out how to fix it.
private void button1_Click(object sender, EventArgs e)
{
this.panel1.Visible = false;
this.panel2.Visible = true;
new Thread(ProgressBAR).Start();
}
private void ProgressBAR()
{
Thread.Sleep(5);
for (int start = 0; start <= 100; start++)
{
this.progressBar1.Value = start;
Thread.Sleep(5);
}
}
推荐答案
您需要使用进度条的Invoke
方法在控件的主线程上执行分配:
You need to use the progress bar's Invoke
method to execute the assignment on the control's primary thread:
this.progressBar1.Invoke((Action) () => this.progressBar1.Value = start, null);
仅当progressBar1.InvokeRequired
为true时才需要这样做.考虑使用此扩展程序类 (无耻的自我推销,对此感到抱歉).然后您就可以忘记自己是否在正确的线程上:
You only have to do this when progressBar1.InvokeRequired
is true. Consider using this extension class (shameless self-promotion, sorry about that). Then you can forget whether or not you are on the right thread:
this.progressBar1.AutoInvoke(() => this.ProgressBar1.Value = start);
这篇关于C#线程访问其他线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文