我試圖實現backgroudworker,但是在第二個線程中不起作用,並且表單仍然是loking,e不能調用我的按鈕2的事件,有人告訴我爲什麼發生這種情況?爲什麼我的backgroundWorker不起作用?
我的代碼:
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork +=
new DoWorkEventHandler(backgroundWorker1_DoWork);
backgroundWorker1.ProgressChanged +=
new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
backgroundWorker1.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
backgroundWorker1.WorkerReportsProgress = true;
}
void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Work is done");
}
void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ThreadProc();
}
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
void ThreadProc()
{
//simulate work
for (int i = 0; i < 100000; ++i)
{
int total = i/1000;
backgroundWorker1.ReportProgress(total);
}
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show("Another thread");
}
TKS;
嗨史蒂夫·迪南,就是這樣,謝謝 – Fernando 2011-05-17 15:10:47