我複製下面的例子Microsoft Thread Example簡單的線程問題
其中給出以下 的代碼,但我上線的錯誤「this.progressBar1.Value =的newval;」指出「跨線程操作無效:從其創建的線程以外的線程訪問的控制'progressBar1'」。
可能是什麼問題? 感謝 DAMO
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");
}
}
UI控件不能從其他線程訪問,你將不得不調用它後面的UI線程上 –
簡單:永遠不要從後臺線程觸摸UI(甚至讀值) 。並沒有像「簡單的線程問題」這樣的事情 - 這是一個矛盾的說法 –
另外,非常重要的是:當後臺線程調用UI線程時,它應該儘快完成,以便UI線程可以保持響應。 –