BlockingCollection class: does the stream have an output if we take blocks?

MSDN has stated that BlockingCollection.Take calls blocks if there are no elements in it. Does this mean that the thread will give a time limit and go to the queue of waiting threads?

If so, does this mean that the thread changes its state to “Done” as soon as the lock collection receives the item and then the next time-list is assigned in accordance with the usual rules?

+3
source share
2 answers

Yes. When you call Take()in BlockingCollection<T>, the thread will block (waiting on the event descriptor) until the item is added to the collection from another thread. This will force this thread to abandon its time fragment.

When an item is added to the collection, a stream will be signaled to continue, receive the item, and continue.

+3
source

I thought it might be interesting to future readers. Here's how I did it for the fact.

class Program
{
    static BlockingCollection<int> queue = new BlockingCollection<int>();
    static Thread th = new Thread(ThreadMethod);
    static Thread th1 = new Thread(CheckMethod);

    static void Main(string[] args)
    {
        th.Start();
        th1.Start();

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

        th.Join();

        Console.ReadLine();
    }

    static void ThreadMethod()
    {
        while (!queue.IsCompleted)
        {
            int r = queue.Take();
            Console.WriteLine(r);
        }
    }

    static void CheckMethod()
    {
        while (!queue.IsCompleted)
        {
            Console.WriteLine(th.ThreadState);
            Thread.Sleep(48);
        }
    }
}
0
source

Source: https://habr.com/ru/post/1750757/


All Articles