我编写代码,用参数调用线程。但我的程序是Windows窗体。那么改变代码,等待线程和程序的GUI如何不冻结?
var t=new Thread(()=>SomeMethod(SomeParameter));
t.Start();
//t.Wait?
答案 0 :(得分:0)
如果您没有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
中发生的事情)。