在递归方法中使用 async/await 的正确方法是什么? [英] What is the correct way to use async/await in a recursive method?

查看:84
本文介绍了在递归方法中使用 async/await 的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在递归方法中使用 async/await 的正确方法是什么?这是我的方法:

What is the correct way to use async/await in a recursive method? Here is my method:

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 的方法:

And here is the method with 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);
 }

推荐答案

虽然我必须预先说明该方法的意图对我来说并不完全清楚,但用一个简单的循环重新实现它是非常简单的:

While I have to say upfront that the intention of the method is not entirely clear to me, reimplementing it with a simple loop is quite trivial:

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;
    }
}

递归不是堆栈友好的,如果您可以选择使用循环,那么在简单的同步场景中绝对值得研究一下(控制不佳的递归最终会导致 StackOverflowExceptions),如以及异步场景,老实说,我什至不知道如果将事情推得太远会发生什么(每当我尝试使用 async方法).

Recursion is not stack-friendly and if you have the option of using a loop, it's something definitely worth looking into in simple synchronous scenarios (where poorly controlled recursion eventually leads to StackOverflowExceptions), as well as asynchronous scenarios, where, I'll be honest, I don't even know what would happen if you push things too far (my VS Test Explorer crashes whenever I try to reproduce known stack overflow scenarios with async methods).

诸如递归和等待/异步关键字之类的答案表明<由于 async/await 状态机的工作方式,code>StackOverflowExceptionasync 的问题不大,但这不是我探索的东西我倾向于尽可能避免递归.

Answers such as Recursion and the await / async Keywords suggest that StackOverflowException is less of a problem with async due to the way the async/await state machine works, but this is not something I have explored much as I tend to avoid recursion whenever possible.

这篇关于在递归方法中使用 async/await 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆