[英]C# backgroundworker advice
我遇到了一个背景工作人员问题-我是线程技术的新手,所以我正尽力做到这一点。
我的主要问题是最终用户只能使用.NET 4.0,因此我无法使用await / async,并且被告知BGW对于我正在使用的框架而言是最好的选择。
我有一个带有gif动画的“请稍候”表单,我想在填充datagridview时加载它。 我需要以某种方式进行检查,以确保它已完成关闭“请稍候”的操作,但是在实现该目标方面有些困难。
public void btnSearch_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
Application.DoEvents();
try
{
this.TestDataTableAdapter.Fill(this.TesteDataData.TestDataTable, txtHotName.Text, ((System.DateTime)(System.Convert.ChangeType(txtDepartFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtDepartTo.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookTo.Text, typeof(System.DateTime)))));
int RowC = TestDataTableDataGridView.RowCount;
if (RowC == 0)
{
MessageBox.Show(GlobVar.NoResults, "", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
catch (System.Exception exc)
{
MessageBox.Show
(
"Problem" +
exc.Message, "An error has occured", MessageBoxButtons.OK, MessageBoxIcon.Warning
);
}
finally
{
//pleaseWait.Close();
}
这是将数据加载到我的DataGridView中的按钮。 到目前为止,这是我的DoWork活动
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
pleaseWait.ShowDialog();
}
由于交叉线程, finally
将无法工作(因此请当前注释掉),但是我需要执行循环/检查以查找DataGridView是否已填充并且操作已完成,然后关闭DoWork
。 或一些如何迫使它跳到RunWorkerCompleted
然后我可以放一个pleaseWait.Close();
在那里。
有什么建议吗?
您必须出示您的pleaseWait
对话框中您的主UI线程,而不是在backgroundWorker1.DoWork
,并隐藏在RunWorkerCompleted
中的事件backgroundWorker1
。 这是this.TestDataTableAdapter.Fill部分,它应该放在backgroundWorker1.DoWork中,因此您的代码应大致如下所示:
public void btnSearch_Click(object sender, EventArgs e)
{
pleaseWait.ShowDialog();
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
this.TestDataTableAdapter.Fill(this.TesteDataData.TestDataTable, txtHotName.Text, ((System.DateTime)(System.Convert.ChangeType(txtDepartFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtDepartTo.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookTo.Text, typeof(System.DateTime)))));
}
catch (System.Exception exc)
{
//You can't show a messagebox here,as it is not in the UI thread
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pleaseWait.Close();
int RowC = TestDataTableDataGridView.RowCount;
if (RowC == 0)
{
MessageBox.Show(GlobVar.NoResults, "", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
当然,在此代码中您会遇到问题,因为TestDataTableAdapter.Fill
代码将无法工作,因为您尝试访问某些TextBoxes
而无法从另一个线程访问。
您有几种解决方案。 在调用backgroundworker并访问此变量而不是TextBoxes
之前,可以使用一些变量来读取值。 或者,您可以使用参数调用背景工作人员。
我建议您阅读有关BackGroundWorker
更多信息,例如在MSDN中 。 还是这个问题,有关发送参数一个BackgroundWorker
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.