在递归方法中使用 async/await 的正确方法是什么?这是我的方法:
public string ProcessStream(string streamPosition)
{
var stream = GetStream(streamPosition);
if (stream.Items.count == 0)
return stream.NextPosition;
foreach(var item in stream.Items) {
ProcessItem(item);
}
return ProcessStream(stream.NextPosition)
}
下面是使用 async/await 的方法:
public async Task<string> ProcessStream(stringstreamPosition)
{
var stream = GetStream(streamPosition);
if (stream.Items.count == 0)
return stream.NextPosition;
foreach(var item in stream.Items) {
await ProcessItem(item); //ProcessItem() is now an async method
}
return await ProcessStream(stream.NextPosition);
}
最佳答案
虽然我不得不预先说明该方法的意图对我来说并不完全清楚,但用一个简单的循环重新实现它是非常简单的:
public async Task<string> ProcessStream(string streamPosition)
{
while (true)
{
var stream = GetStream(streamPosition);
if (stream.Items.Count == 0)
return stream.NextPosition;
foreach (var item in stream.Items)
{
await ProcessItem(item); //ProcessItem() is now an async method
}
streamPosition = stream.NextPosition;
}
}
递归不是堆栈友好的,如果您可以选择使用循环,那么在简单的同步场景(其中控制不佳的递归最终导致 StackOverflowException
s)以及异步场景中,它绝对值得研究,老实说,我什至不知道如果你把事情推得太远会发生什么(每当我尝试使用 async
方法重现已知的堆栈溢出场景时,我的 VS 测试资源管理器就会崩溃)。
诸如 Recursion and the await / async Keywords 之类的答案建议StackOverflowException
async
问题不大由于方式 async/await
状态机可以工作,但这不是我探索过的东西,因为我倾向于尽可能避免递归。
关于c# - 在递归方法中使用 async/await 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25007709/