Create empty IAsyncEnumerable

你说的曾经没有我的故事 提交于 2020-01-23 04:18:06

问题


I have an interface which is written like this:

public interface IItemRetriever
{
    public IAsyncEnumerable<string> GetItemsAsync();
}

I want to write an empty implementation that returns no item, like so:

public class EmptyItemRetriever : IItemRetriever
{
    public IAsyncEnumerable<string> GetItemsAsync()
    {
       // What do I put here if nothing is to be done?
    }
}

If it was a plain IEnumerable, I would return Enumerable.Empty<string>();, but I didn't find any AsyncEnumerable.Empty<string>().

Workarounds

I found this which works but is quite weird:

public async IAsyncEnumerable<string> GetItemsAsync()
{
    await Task.CompletedTask;
    yield break;
}

Any idea?


回答1:


If you install the System.Linq.Async package, you should be able to use AsyncEnumable.Empty<string>(). Here's a complete example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        IAsyncEnumerable<string> empty = AsyncEnumerable.Empty<string>();
        var count = await empty.CountAsync();
        Console.WriteLine(count); // Prints 0
    }
}



回答2:


If for any reason you don't want to install the package which is mentioned in Jon's answer, you can create the method AsyncEnumerable.Empty<T>() like this:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public static class AsyncEnumerable
{
    public static IAsyncEnumerator<T> Empty<T>() => EmptyAsyncEnumerator<T>.Instance;

    class EmptyAsyncEnumerator<T> : IAsyncEnumerator<T>
    {
        public static readonly EmptyAsyncEnumerator<T> Instance = 
            new EmptyAsyncEnumerator<T>();
        public T Current => default!;
        public ValueTask DisposeAsync() => default;
        public ValueTask<bool> MoveNextAsync() => new ValueTask<bool>(false);
    }
}

Note: The answer doesn't discourage using the System.Linq.Async package. This answer provides a brief implementation of AsyncEnumerable.Empty<T>() for cases that you need it and you cannot/don't want to use the package. You can find the implementation used in the package here.



来源:https://stackoverflow.com/questions/59443429/create-empty-iasyncenumerable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!