开发者

BlockingCollection class: Does thread yield if Take blocks?

开发者_如何学运维MSDN said that BlockingCollection.Take call blocks if there is no elements in it. Does it mean the thread will yield the timeslice and go to the waiting threads queue?

If yes does it mean that the thread will change its state to Ready once the blocking collection received an item and then will be scheduled to next timeslice as per usual rules?


Yes. When you call Take() on a BlockingCollection<T>, the thread will sit blocked (waiting on an event handle) until an element is added to the collection from another thread. This will cause that thread to give up its time slice.

When an element is added to the collection, the thread will get signaled to continue, get the element, and continue on.


I thought this might be interesting for further readers. This is how I established this for 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜