编辑 我想强制等待异步调用工作人员的正确方法是使用Task.Run,如下所示:
await Task.Run(() => builder.Build(dlg.FileName, cts.Token, new Progress(ReportProgress)));
从http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/10293335.aspx得到了一些启发。
这应该很容易,但我是异步/等待的新手,所以请耐心等待。我正在构建一个类库,以公开具有一些长时间运行的操作的 API。过去,我使用 BackgroundWorker 来处理进度报告和取消,就像在这个简化的代码片段中一样:
public void DoSomething(object sender, DoWorkEventArgs e)
{
BackgroundWorker bw = (BackgroundWorker)sender;
// e.Argument is any object as passed by consumer via RunWorkerAsync...
do
{
// ... do something ...
// abort if requested
if (bw.CancellationPending)
{
e.Cancel = true;
break;
} //eif
// notify progress
bw.ReportProgress(nPercent);
}
}
客户端代码如下:
BackgroundWorker worker = new BackgroundWorker
{ WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
worker.DoWork += new DoWorkEventHandler(_myWorkerClass.DoSomething);
worker.ProgressChanged += WorkerProgressChanged;
worker.RunWorkerCompleted += WorkerCompleted;
worker.RunWorkerAsync(someparam);
现在我想利用新的异步模式。所以,首先是我如何在我的 API 中编写一个简单的长时间运行的方法;在这里,我只是逐行读取文件,只是为了模拟一个真实的过程,我必须通过一些处理来转换文件格式:
public async Task DoSomething(string sInputFileName, CancellationToken? cancel, IProgress progress)
{
using (StreamReader reader = new StreamReader(sInputFileName))
{
int nLine = 0;
int nTotalLines = CountLines(sInputFileName);
while ((sLine = reader.ReadLine()) != null)
{
nLine++;
// do something here...
if ((cancel.HasValue) && (cancel.Value.IsCancellationRequested)) break;
if (progress != null) progress.Report(nLine * 100 / nTotalLines);
}
return nLine;
}
}
为了这个示例,假设这是一个 DummyWorker 类的方法。现在,这是我的客户端代码(一个 WPF 测试应用程序):
private void ReportProgress(int n)
{
Dispatcher.BeginInvoke((Action)(() => { _progress.Value = n; }));
}
private async void OnDoSomethingClick(object sender, RoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog { Filter = "Text Files (*.txt)|*.txt" };
if (dlg.ShowDialog() == false) return;
// show the job progress UI...
CancellationTokenSource cts = new CancellationTokenSource();
DummyWorker worker = new DummyWorker();
await builder.Build(dlg.FileName, cts.Token, new Progress(ReportProgress));
// hide the progress UI...
}
IProgress 接口的实现来自http://blog.stephencleary.com/2010/06/reporting-progress-from-tasks.html,因此您可以参考该 URL。无论如何,在这个使用测试中,UI 被有效地阻止了,我看不到任何进展。那么参考消费代码,这种情况的全貌是什么?