我得到了一些非常简单的代码,但无法让它工作。我正在使用BackgroundWorker。问题是RunWorkerCompleted是以快速方式解决的。运行后立即我收到消息“工作完成”,但应用程序仍然冻结了几秒钟,因为'DataType data = new DataType(path);'是执行的。之后,我正确填充了所有DataGridViews等。如果我用Thread.Sleep交换这一行,一切似乎都运行良好。有什么想法吗?
public frmWindow(string path)
{
InitializeComponent();
DataType d;
backgroundWorker1.RunWorkerAsync(path);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string path = e.Argument as string;
DataType data = new DataType(path);
e.Result = data;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
d = e.Result as DataType;
MessageBox.Show("Work completed");
}
答案 0 :(得分:1)
如何使用Debug.Write代替带有计时器的MessageBox.Show来显示何时输入和退出方法。
虽然这个相同的后台线程可以在你的UI上运行,但它几乎总是不是一件好事 - UI不是线程安全的。
BackgroundWorker backGroundWorker1;
public frmWindow(string path)
{
InitializeComponent();
DataType d;
backGroundWorker1 = new BackgroundWorker();
backGroundWorker1.DoWork += (s, e) =>
{
System.Diagnostics.Debug.Write("Work started at: " + DateTime.Now + Environment.NewLine);
string path = e.Argument as string;
DataType data = new DataType(path);
e.Result = data;
};
backGroundWorker1.RunWorkerCompleted += (s, e) =>
{
d = e.Result as DataType;
System.Diagnostics.Debug.Write("Work completed at: " + DateTime.Now + Environment.NewLine);
};
backGroundWorker1.RunWorkerAsync();
}