我有一个连接到 API、扫描文件并检查其状态的简单应用程序。扫描可能需要一段时间,我想每 5 秒向 api 询问一次文件状态,如果它是干净的 - 返回 true,如果其他 - 返回 false。 问题是我不知道如何告诉程序在返回值之前等到满足条件。我的代码看起来像这样:
bool Scan(string filePath){
Scanner.Scan(filePath);
//now repeat line below every 2s until the result is positive
var result = Scanner.CheckStatus();
// I dont want to go below before status is positive or x seconds has elapsed
return result
}
最佳答案
async/await
方法看起来很清楚。即使您没有 UI,也可以使用 async/await
。
async Task<bool> Scan(string filePath)
{
Scanner.Scan(filePath);
var result = Scanner.CheckStatus();
while(result == false)
{
await Task.Delay(2000);
result = Scanner.CheckStatus();
}
return result
}
因为您的 Scanner.Scan
方法与 IO 一起工作 - 它成为使用 async/await
的异步方法的非常好的候选者。
关于c# - 定时器结束后的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40843278/