我需要调用一个以下方式工作的web API:
- 上传一首歌曲
- 请求对该歌曲进行特定分析
- 等待进程完成
- 检索并返回结果
我在第三步遇到问题,我尝试了Thread.Sleep
但这会冻结UI。
如何在任务中等待而不冻结UI?
public override async Task Execute(Progress<double> 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<AnalyzeTempoResponse>(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<double>(ProgressHandler), Id);
}
private AnalyzeTempoResponse _response;
private void target(AnalyzeTempoResponse obj)
{
_response = obj;
}
await Task.Delay(x)
的众多重复项之一。 - Scott Chamberlain