-
Imagine an interface with a method for streaming data items. Typically, the items are fetched from the network so public interface IDataSource
{
IAsyncEnumerable<Foo> GetFoosAsync();
}
internal sealed class LocalTestDataSource : IDataSource
{
public IAsyncEnumerable<Foo> GetFoosAsync()
{
throw new NotImplementedException();
}
private readonly IEnumerable<Foo> foos = Enumerable.Range(0, 100).Select(x => new Foo(x));
} I can't seem to find an API that allows me to wrap the synchronous enumerable as an asynchronous one. I guess this is intentional because it can create a "sync-over-async" pit of failure. However, in this case it is not relevant because the code is not actually performing any I/O. Yielding without actually awaiting works, but the resulting code generates CS1998. // CS1998: This async method lacks 'await' operators and will run synchronously.
public async IAsyncEnumerable<Foo> GetFoosAsync()
{
foreach (Foo foo in foos)
{
yield return foo;
}
} What is the recommended course of action in this situation? Some I have considered:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
One option would be to write an explicit async enumerator to wrap the non-async enumerator (option 3 in your list):
Usage:
|
Beta Was this translation helpful? Give feedback.
-
In cases like this, I simply ignore that warning. The warning is a notification, to ensure I know what's going on. It's not a blocker. |
Beta Was this translation helpful? Give feedback.
One option would be to write an explicit async enumerator to wrap the non-async enumerator (option 3 in your list):