如何使用参数等待线程并且不冻结主线程

时间:2014-08-18 14:32:54

标签: c#

我编写代码,用参数调用线程。但我的程序是Windows窗体。那么改变代码,等待线程和程序的GUI如何不冻结?

var t=new Thread(()=>SomeMethod(SomeParameter));
t.Start();
//t.Wait?

1 个答案:

答案 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中发生的事情)。