我正在編寫一個WPF應用程序的團隊。我們必須這樣做,以便當用戶隱藏/顯示不同的列時,它將反映在其中一個視圖的ReportViewer控件中。在測試中,我們發現將數據添加到ReportViewer的數據源需要很長時間;有時大約幾秒到可能一分鐘。太長時間我想爲用戶。所以我試圖使用C#的異步並等待。但是,當我申請等待進程管理線然後編譯它時,我從C#編譯器中得到一個錯誤,「無法等待'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();
}
如果您認爲等待需要很長時間的事情是解決您的問題的方法,那麼您必須對「await」的做法產生誤解。你能描述一下你的信念是關於「等待」嗎?只有等待已經*異步的東西纔有意義;你相信等待*使*不是異步操作的異步操作?它不是。 –
我的理解是,使用async/await可以將控制返回到UI線程,而不是掛起它,等待一些長時間的工作過程完成。但是謝謝你的提問。 – Rod
我的觀點是,如果函數無效返回*和*已經異步然後*它不應該花費太多時間*。如果它無效返回,同步和高延遲,那麼沒有什麼可以「等待」。等待管理現有的異步操作。如果你有一個你想要異步的高延遲操作,'await'不會幫助你。你將不得不弄清楚如何通過其他機制來實現異步。 –