没有冻结替代Thread.Sleep等待在任务内部
我必须调用一个如下工作的Web API:
- 上传一首歌
- 请求对该歌曲进行特定分析
- 等待该过程完成
- 检索并返回结果
我遇到了问题。 3,我尝试过Thread.Sleep
但冻结了UI。
如何在不冻结UI的情况下等待任务?
public override async Task Execute(Progress progress, string id) { FileResponse upload = await Queries.FileUpload(id, FileName, progress); upload.ThrowIfUnsucessful(); FileResponse analyze = await Queries.AnalyzeTempo(id, upload); analyze.ThrowIfUnsucessful(); FileResponse status; do { status = await Queries.FileStatus(id, analyze); status.ThrowIfUnsucessful(); Thread.Sleep(TimeSpan.FromSeconds(10)); } while (status.File.Status != "ready"); AnalyzeTempoResponse response = await Queries.FileDownload(id, status); response.ThrowIfUnsucessful(); Action(response); }
编辑:这就是我称之为任务的方式
async void MainWindow_Loaded(object sender, RoutedEventArgs e) { var fileName = @"d:\DJ SRS-Say You Never Let Me Go.mp3"; TempoAnalyzeTask task = new TempoAnalyzeTask(fileName, target); await task.Execute(new Progress(ProgressHandler), Id); } private AnalyzeTempoResponse _response; private void target(AnalyzeTempoResponse obj) { _response = obj; }
对于最小的更改,只需切换到Task.Delay
并await
结果。 当你等待10秒时,这不会阻止你的UI,就像你的其他三个await
s一样
FileResponse status; do { status = await Queries.FileStatus(id, analyze); status.ThrowIfUnsucessful(); await Task.Delay(TimeSpan.FromSeconds(10)); } while (status.File.Status != "ready");