PPC
PPC

Reputation: 1913

How to enumerate an IEnumerable while another thread populates it

I want two threads on the same machine, one that populates a collection and the other one that pops data out of it as soon as it's available and stops when it know it's over. I just don't know what collection to use...

private void DataProviderThread()
{
    GlobalCollection = new SomeMagicCollection();

    for (int i = 0; i < 100; i++)
    {
        GlobalCollection.Add(new SomeDataItem(i));
        Thread.Sleep(100);
    }

    GlobalCollection.IHaveFinishedPopulatingThanksAndBye();
}

private void DataCruncherThread()
{
    foreach (var item in GlobalCollection)
    {
        // Do whatever
    }
    // The control should exit foreach only once the data provider states that the collection is finished  
}

I then want to iterate simply on it, having the Collection take care of

I can't believe C# doesn't ship this in a new version. But what's its name?

Upvotes: 3

Views: 154

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273274

What you have is a classic Producer/Consumer pattern.

You can use a ConcurrentQueue<T> or, probably better, a BlockingCollection<T>

The BoundedCapacity property lets you regulate (throttle) the dataflow.

It is an IEnumerable<T> but don't try to use it like non-shared collection. The TryTake() method is the most useful way to get your data.

Upvotes: 8

Related Questions