是否有可能做这样的事情,或者这是危险的/不好的做法吗?如果效果不好,还有什么解决方法?
void methodA ()
{
while (something) {
// do stuff
methodB();
}
}
async Task methodB()
{
bool b = await methodC();
// do something with b
}
async Task<bool> methodC()
{
await Task.Delay(1000);
}
我想要实现的是 methodA
能够在 methodC
等待 IO 时执行某些操作。因此,我希望 methodC
在忙碌时返回到 methodB
,并且由于 methodB
等待答案,它将返回到 methodA
,其中 methodA
可以继续处理内容并可能再次调用 methodB
最佳答案
不等待 MethodA 中的 MethodB 可能是完全可以接受的(只要在 MethodA 中执行其他操作之前实际上不需要 MethodB 完成,并且小心避免竞争条件)。不过还有其他一些选择。
您可能想看看 Task.ContinueWith .
我非常喜欢这里的第二个选项:
List<Task> tasks = new List<Task>();
while (something) {
// do stuff
// This doesn't actually wait for methodB - it just keeps going
Task methodBTask = methodB();
tasks.Add(methodBTask);
}
// Wait for all of the tasks we started to complete
await Task.WhenAll(tasks);
// ...
我认为这应该可以满足您的需求,并且不会出现竞争条件。基本上,这将启动 MethodB 中的任何操作,无论您想要执行多少次,然后等待它们全部“排队”后完成。
关于C# 嵌套异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41149927/