I have a situation where I am launching Task-s
and I want their results to somehow be piped/enqueued in a datastructure as fast as possible, not caring on their order.
Does IAsyncEnumerable
fit for this situation?
public async Task BigMethod()
{
Queue<int> queue = new Queue<int>();
foreach (var item in RunJobsAsync())
{
queue.Enqueue(item);
}
//await foreach(var item in await RunIAsyncJobsAsync())
// {
// queue.Enqueue(item);
// }
// [some more code]
}
Without IAsyncEnumerable
public async Task<IEnumerable<int> RunJobsAsync()
{
List<Task<int>> tasks = new List<Task<int>>();
foreach(var x in Enumerable.Range(0,100))
{
tasks.Add(Task.Run(async()=> await someMethodAsync()));
}
await tasks.WhenAll(tasks);
return tasks.Select(x=>x.Result);
}
With IAsyncEnumerable
public async IAsyncEnumerable<int> RunIAsyncJobsAsync()
{
foreach (var x in Enumerable.Range(0, 100))
{
yield return await Task.Run(async () => await someMethodAsync());
}
}
Is there any performance gain with IAsyncEnumerable
since I want in the end to not move with the algorithm further until all async
calls have been finished, but I would like them to execute in parallel, thus instead of waiting all of them sequentially , I'd like to just wait for the longest one to complete.
P.S In this scenario would I need a ConcurrentQueue
/locking ?