No-freezes alternative to Thread.Sleep for waiting inside a task

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

  • upload song
  • request a specific analysis of this song
  • wait for the process to complete.
  • get and return the result

I have a problem with no. 3, I tried Thread.Sleep, but it freezes the user interface.

How can I wait in a task without freezing the user interface?

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: so 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;
}
+3
source share
1 answer

For minimal changes, just switch to Task.Delayand awaitresult. This no longer blocks your user interface while you wait 10 seconds, like the 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");
+6

All Articles