No-freezes alternative to Thread.Sleep for waiting inside a Task [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-23 12:14:25

问题


I have to call a web API that works as follows :

  1. upload a song
  2. request a particular analysis on that song
  3. wait that the process is finished
  4. retrieve and return the result

I am having a problem with no. 3, I've tried Thread.Sleep but that freezes the UI.

How can I wait in a task without freezing the 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);
}

EDIT : this is how I call the task

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:


For minimal changes just switch to Task.Delay and await the result. This no longer blocks your UI while you wait 10 seconds just like your other three awaits

FileResponse status;
do
{
    status = await Queries.FileStatus(id, analyze);
    status.ThrowIfUnsucessful();
    await Task.Delay(TimeSpan.FromSeconds(10));
} while (status.File.Status != "ready");


来源:https://stackoverflow.com/questions/21890513/no-freezes-alternative-to-thread-sleep-for-waiting-inside-a-task

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!