问题
I have to call a web API that works as follows :
- upload a song
- request a particular analysis on that song
- wait that the process is finished
- 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 await
s
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