我有一个Main表单,它正在运行同步操作(从而冻结表单)。 在开始发生之前,我调用我的函数showWaitWindow()。
private void showWaitWindow()
{
Wait x = new Wait();
x.Show(this); //"this" is allowing the form to later centralize itself to the parent
}
这就是它正好发生的地方:
if (result)
{
System.Threading.Thread t = new System.Threading.Thread(new
System.Threading.ThreadStart(showWaitWindow));
t.Start();
}
else
{
return;
}
propertyGrid1.SelectedObject = z.bg_getAllPlugins(); //Heavy synchronous call
//This should be closing the form, which is not happening.
for (int index = Application.OpenForms.Count; index >= 0; index--)
{
if (Application.OpenForms[index].Name == "Wait")
{
MessageBox.Show("found");
Application.OpenForms[index].Close();
}
}
我在没有线程的情况下尝试了这个,但是效果不好。此外,因为它试图集中到父节点,而在另一个线程中创建,它会抛出一个异常“试图在不同的线程中访问它是在”改写“中创建的。
我该如何处理?
答案 0 :(得分:1)
我建议使用WinForms工具箱中提供的BackgroundWorker
。
public partial class Form1 : Form
{
private BackgroundWorker backgroundWorker1;
public Form1()
{
InitializeComponent();
this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker();
this.backgroundWorker1.DoWork += new System.ComponentModel.DoWorkEventHandler(this.backgroundWorker1_DoWork);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//perform lengthy operation in here.
}
}