我写的代码,调用线程的参数。但我的程序是windows窗体。那么,如何更改代码,等待线程和程序的GUI不冻结呢?
var t=new Thread(()=>SomeMethod(SomeParameter));
t.Start();
//t.Wait?
如果您没有可用的await
,最简单的解决方案是使用BackgroundWorker
:
var bw = new BackgroundWorker();
bw.DoWork += (sender, args) => {
// do your lengthy stuff here -- this will happen in a separate thread
...
}
bw.RunWorkerCompleted += (sender, args) => {
if (args.Error != null) // if an exception occurred during DoWork,
MessageBox.Show(args.Error.ToString()); // do your error handling here
// Put here the stuff you wanted to put after `t.Wait`
...
}
bw.RunWorkerAsync(); // start the background worker
RunWorkerCompleted
在UI线程中运行,因此您将能够在那里更新您的UI(与DoWork
中发生的事情相反)。