我所在的团队正在编写 WPF 应用程序。我们必须做到这一点,以便当用户隐藏/显示不同的列时,它会在视图之一的 ReportViewer 控件中反映出来。在测试中我们发现将数据添加到ReportViewer的数据源需要很长时间;有时大约几秒钟到可能一分钟。我认为对于用户来说太长了。所以我尝试使用C#的async和await。但是,当我将await 应用于进程占用者行并编译它时,我从C# 编译器收到错误“Cannot wait 'void'”。在这种情况下,我无法更改 .NET 框架返回的内容,它是无效的。那么我该如何处理这种情况呢?这是代码:
private async Task GenerateReportAsync()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Clear();
int iCols = 0;
//Get the column names
if (Columns.Count == 0) //Make sure it isn't populated twice
{
foreach (DataGridColumn col in dataGrid.Columns)
{
if (col.Visibility == Visibility.Visible)
{
Columns.Add(col.Header.ToString()); //Get the column heading
iCols++;
}
}
}
//Create a DataTable from the rows
var itemsSource = dataGrid.ItemsSource as IEnumerable<Grievance>;
if (this.rptViewer != null)
{
rptViewer.Reset();
}
rptViewer.LocalReport.DataSources.Clear();
if (m_rdl != null)
{
m_rdl.Dispose();
}
Columns = GetFieldOrder();
m_rdl = CoreUtils.GenerateRdl(Columns, Columns);
rptViewer.LocalReport.LoadReportDefinition(m_rdl);
//the next line is what takes a long time
await rptViewer.LocalReport.DataSources.Add(new ReportDataSource("MyData", CoreUtils.ToDataTable(itemsSource)));
rptViewer.RefreshReport();
}
对于本质上同步的方法,您需要将它们包装在您自己的中Task
所以你可以等待。在你的情况下,我只会使用Task.Run
:
await Task.Run(() =>
{
rptViewer.LocalReport.DataSources.Add(new ReportDataSource("MyData", CoreUtils.ToDataTable(itemsSource)));
});
还有其他方法可以生成任务,但这可能是最简单的。如果这更新了 UI 组件,它可能会引发异常,因为这些操作必须发生在 UI 线程上。在这种情况下,请尝试将 UI 相关部分从长时间运行的部分中取出,并仅将长部分包装在Task
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)