Reputation: 1539
I have a situation where I would like to stream data of the same type from several sources asynchronously. The data results should go out as they comes in. What is the easiest way to do this? yield return is blocking so this is not doing what I want. In the example below I would like the data from source B to output before the data from source A.
List<string> GetComputerRecordsFromA(int computerId)
{
Thread.sleep(100);
return new List<Record> {"Record1","Record2","Record3"};
}
List<int> GetComputerRecordsFromB()
{
return new List<int> {"Record1","Record2","Record3"};
}
IEnumerable<List<int>> GetDataBlocks()
{
//How to yield out in the order data comes available??
var computerIds = new List<int> {1,3,99,4};
foreach(int id in computerIds)
{
yield return GetDataFromA();
yield return GetDataFromB();
}
}
Upvotes: 2
Views: 46
Reputation: 39023
You can do things concurrently - use a BlockingCollection
and a few threads. One thread for each input and one - your main thread probably - that yield-returns items from the list.
Just note that you might not reach the end of the list - if your reader is faster than your writers, it will think it got to the end of the list even though the writers will write more data to the list later.
Upvotes: 1