// sample 1 use BackgroundWorker, it works fine
private BackgroundWorker workerPorcee = new BackgroundWorker();
private void button1_Click(object sender, EventArgs e)
{
workerPorcee.DoWork += new DoWorkEventHandler(workerPorcee_DoWork);
workerPorcee.ProgressChanged += new ProgressChangedEventHandler(workerPorcee_ProgressChanged);
workerPorcee.RunWorkerCompleted += new RunWorkerCompletedEventHandler(workerPorcee_RunWorkerCompleted);
workerPorcee.WorkerReportsProgress = true;
workerPorcee.RunWorkerAsync();
}
void workerPorcee_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
void workerPorcee_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
workerPorcee.ReportProgress(i);
Thread.Sleep(100);
}
}
void workerPorcee_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.progressBar1.Value = 100;
}
我只是实现了我的工作线程,但它会出现异常:跨线程操作无效:控件'progressBar1'从创建它的线程以外的线程访问。
// my worker thread
private void button3_Click(object sender, EventArgs e)
{
Worker wk = new Worker();
Thread thr = new Thread(new ThreadStart(wk.ProcessEvent));
wk.ProgressChanged += new delCallback(wk_ProgressChanged);
thr.Start();
}
void wk_ProgressChanged(int percent)
{
this.progressBar1.Value = percent;
//exception:Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on.
}
public delegate void delCallback(int percent);
public class Worker
{
public event delCallback ProgressChanged;
public void ProcessEvent()
{
for (int i = 0; i < 100; i++)
{
if (ProgressChanged != null)
{
this.ProgressChanged(i);
}
Thread.Sleep(100);
}
}
}
WinForm,我只想使用我的工作线程来设置进度条值,但它失败了。任何人帮助指出什么问题?如何实现与 BackgroundWorker 一样的功能?