所以我正在寫一個方法,該方法應該處理大量的字符串並更新處理過的每個字符串的UI。我正在使用async-await
模式來使用Progress記者,它將字符串報告給應該更新的主線程。 問題是:它不起作用。即使我使用了await關鍵字,用戶界面也會被阻塞,就好像該方法同步運行一樣。 這裏是我的代碼如下所示:如何讓我的異步方法阻止用戶界面?
private async Task ProcessFile(string filePath, IProgress<string> progress)
{
string[] LinesToProcess = File.ReadAllLines(filePath);
int LineCount = Buffer.Count();
await Task.Factory.StartNew(() =>
{
for (int i = 0; i < Buffer.Count(); i++)
{
//Do actual processing here
progress.Report(string.Format("Lines processed: {0}/{1}", i, LineCount));
}
});
}
而這裏的調用ProcessFile
任務
private async Task RunTask()
{
string filePath = //Get filePath somehow
await ProcessFile(filePath, new Progress<string>(line =>
{
ProcessedLabel.Text = line;
}));
}
的方法最後,這裏的按鈕回調的RunTask()任務有關:
private async void Button_Click(object sender, EventArgs e)
{
await RunTask();
}
我簡化了代碼的可讀性。任何幫助是極大的讚賞。謝謝!
'File.ReadAllLines(filePath);'會這樣做,讀取所有行,所以如果存在多行的話,您最好逐行讀取。這可能有幫助。我只是新來的異步我自己 –
你有沒有嘗試添加ConfigureAwait(false)到ProcessFile函數調用,因爲很多次我看到了UI塊。 – Chasefornone