Is it possible to “await yield return DoSomethingAsync()”

前端 未结 9 964
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 14:08

Are regular iterator blocks (i.e. \"yield return\") incompatible with \"async\" and \"await\"?

This gives a good idea of what I\'m trying to do:

asyn         


        
9条回答
  •  伪装坚强ぢ
    2020-11-27 14:29

    This feature will be available as of C# 8.0. https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/

    From MSDN

    Async streams

    The async/await feature of C# 5.0 lets you consume (and produce) asynchronous results in straightforward code, without callbacks:

    async Task GetBigResultAsync()
    {
        var result = await GetResultAsync();
        if (result > 20) return result; 
        else return -1;
    }
    

    It is not so helpful if you want to consume (or produce) continuous streams of results, such as you might get from an IoT device or a cloud service. Async streams are there for that.

    We introduce IAsyncEnumerable, which is exactly what you’d expect; an asynchronous version of IEnumerable. The language lets you await foreach over these to consume their elements, and yield return to them to produce elements.

    async IAsyncEnumerable GetBigResultsAsync()
    {
        await foreach (var result in GetResultsAsync())
        {
            if (result > 20) yield return result; 
        }
    }
    

提交回复
热议问题