C# 没有冻结线程的替代方法。在任务内部等待时睡眠
我必须调用一个web API,其工作原理如下:C# 没有冻结线程的替代方法。在任务内部等待时睡眠,c#,multithreading,task,wait,C#,Multithreading,Task,Wait,我必须调用一个web API,其工作原理如下: 上传一首歌 要求对那首歌进行特别的分析 等待进程完成 检索并返回结果 我的3号有问题,我尝试了Thread.Sleep,但这会冻结UI 如何在任务中等待而不冻结UI public override async Task Execute(Progress<double> progress, string id) { FileResponse upload = await Queries.FileUpload(id, FileNam
Thread.Sleep
,但这会冻结UI
如何在任务中等待而不冻结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);
}
公共重写异步任务执行(进度,字符串id)
{
FileResponse upload=等待查询。FileUpload(id、文件名、进度);
upload.throwifuncessful();
FileResponse analyze=wait querys.AnalyzeTempo(id,upload);
analyze.throwifuncessful();
文件响应状态;
做
{
status=wait querys.FileStatus(id,analyze);
status.throwifuncessful();
睡眠(时间跨度从秒(10));
}while(status.File.status!=“就绪”);
AnalyzeTempoResponse response=等待查询。文件下载(id、状态);
response.throwifuncessful();
行动(回应);
}
编辑:这就是我对任务的称呼
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;
}
async void主窗口\u已加载(对象发送方,路由目标)
{
var fileName=@“d:\DJ SRS说你永远不会让我走。mp3”;
TempoAnalyzeTask task=新的TempoAnalyzeTask(文件名,目标);
等待任务。执行(新进度(ProgressHandler),Id);
}
私人分析临时响应;
私有无效目标(AnalyzeTempoResponse obj)
{
_响应=obj;
}
对于最小的更改,只需切换到并等待结果。这将不再像其他三个wait
s那样在等待10秒时阻塞用户界面
FileResponse status;
do
{
status = await Queries.FileStatus(id, analyze);
status.ThrowIfUnsucessful();
await Task.Delay(TimeSpan.FromSeconds(10));
} while (status.File.Status != "ready");
是的,我正试图找出如何翻译您发送到
任务的链接,而不是BackgroundWorker
@bzlm。我同意,但最好将其指向显示如何使用等待任务的众多副本中的一个。在其中一个答案中延迟(x)
。正是这样,谢谢!这是我见过的最好的例子。