在Thread.Sleep中没有冻结替代等待在Task内部

时间:2014-02-19 19:33:33

标签: c# multithreading task wait

我必须调用一个如下工作的Web API:

  1. 上传一首歌
  2. 要求对该歌曲进行特定分析
  3. 等待该流程已完成
  4. 检索并返回结果
  5. 我遇到了问题。 3,我尝试了Thread.Sleep,但冻结了用户界面。

    如何在不冻结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;
    }
    

1 个答案:

答案 0 :(得分:6)

对于最小的更改,只需切换到Task.Delayawait结果即可。与其他三个await

一样,等待10秒后,这不再会阻止您的用户界面
FileResponse status;
do
{
    status = await Queries.FileStatus(id, analyze);
    status.ThrowIfUnsucessful();
    await Task.Delay(TimeSpan.FromSeconds(10));
} while (status.File.Status != "ready");