我有两个看起来像这样的线程
pbDB_running = true; // start progress bar
Thread connectDb = new Thread(new ThreadStart(ConnectToDb));
Thread runProgress = new Thread(new ThreadStart(RunpbDB));
connectDb.Start();
runProgress.Start();
connectDb.Join(); //wait untill the connection is done
pbDB_running = false; //stop the progress bar
您可能已经猜到了,ConnectToDb 用于连接数据库,而 runpbDB 用于在界面上运行进度条。进度条 (pbDB) 是在设计视图上通过拖放创建的 Windows.Forms 控件。runProgress 线程正在运行 RunpbDB() ,看起来像这样:
private void RunpbDB()
{
while (pbDB_running)
{
if (pbDB.Value == 100) pbDB.Value = 0;
else pbDB.Value += 1;
}
pbDB.Value = 0;
}
当两个线程启动时,我在 RunpbDB() 中得到以下异常:
Cross-thread operation not valid: Control 'pbDB' accessed from a thread other than the thread it was created on.
我能做些什么来克服这种情况?