Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 373
aybe Avatar asked Feb 19 '14 19:02

aybe


People also ask

What can I use instead of sleep in Java?

For your case I would suggest a spinning loop instead.

Does await task delay block thread?

await Task. Delay(1000) doesn't block the thread, unlike Task. Delay(1000).


1 Answers

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");
like image 189
Scott Chamberlain Avatar answered Nov 14 '22 22:11

Scott Chamberlain