我复制了以下示例Microsoft Thread 示例
它给出了下面的代码,但我在“this.progressBar1.Value = newval;”行出现错误 声明“跨线程操作无效:控件'progressBar1'从创建它的线程以外的线程访问。”
可能是什么问题?谢谢达摩
C# 代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread trd = new Thread(new ThreadStart(this.ThreadTask));
trd.IsBackground = true;
trd.Start();
}
private void ThreadTask()
{
int stp;
int newval;
Random rnd = new Random();
while (true)
{
stp = this.progressBar1.Step * rnd.Next(-1, 2);
newval = this.progressBar1.Value + stp;
if (newval > this.progressBar1.Maximum)
newval = this.progressBar1.Maximum;
else if (newval < this.progressBar1.Minimum)
newval = this.progressBar1.Minimum;
this.progressBar1.Value = newval;
Thread.Sleep(100);
}
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("This is the main thread");
}
}