【发布时间】:2017-03-21 17:09:28
【问题描述】:
我有一个表单,它在单击按钮时从DataGridView 运行查询。下面的代码按我的预期工作;
- 打开一个显示“查询运行时请稍候”的表单
- 运行查询
- 加载时关闭表单,然后用 数据。
我添加了一个带有简单 gif 的图片框 - 纯粹是为了让 UI 和用户看到它正在工作。但 gif 实际上并没有旋转 - 只是显示为图片。测试它,如果我自己在表单上运行它就可以了,我只能冒险猜测正在运行的查询正在阻止它按应有的方式工作。
PleaseWaitForm pleaseWait = new PleaseWaitForm();
try
{
pleaseWait.Show();
Application.DoEvents();
this.singleCenTableAdapter.Fill(this.singleCenData.SingleCenTable, ((System.DateTime)(System.Convert.ChangeType(txtBookFrom.Text, typeof(System.DateTime)))), ((System.DateTime)(System.Convert.ChangeType(txtBookTo.Text, typeof(System.DateTime)))));
int RowC = singleCenTableDataGridView.RowCount;
pleaseWait.Close();
if (RowC == 0)
{
MessageBox.Show(GlobVar.NoResults, "", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
pleaseWait.Close();
}
catch (System.Exception exc)
{
GlobVar.vid.Open();
var LogName = GlobVar.LoginName.ExecuteScalar();
GlobVar.vid.Close();
MessageBox.Show
(
"An error has occured " + LogNam + ". Please try again. \n\n" +
exc.Message, "An error has occured", MessageBoxButtons.OK, MessageBoxIcon.Warning
);
}
finally
{
pleaseWait.Close();
}
“请稍候”表单只是一个标签和图片,所以此时只有 Initalize ;
public PleaseWaitForm()
{
InitializeComponent();
}
是否有人对如何解决此问题以使其正常工作有任何想法?或者我做错了什么特别的事情?我知道在大多数情况下我可能会因为使用Application.DoEvents() 而得到一些支持,但我们不胜感激!
【问题讨论】:
-
你可以使用Thread或者BackgroundWorker来实现。
-
您可以使用
async和await来保持您的用户界面响应。见Asynchronous Programming with async and await (C#)。或者,您可以使用Task-based Asynchronous Programming,但async和await更简单,应该足以解决您的问题。 -
@Rajendra
async、await和 TPL 旨在取代Thread和BackgroundWorker。
标签: c#