简体   繁体   English

BlockingCollection类:如果Take块,线程是否会产生?

[英]BlockingCollection class: Does thread yield if Take blocks?

MSDN said that BlockingCollection.Take call blocks if there is no elements in it. MSDN说BlockingCollection.Take调用块,如果没有元素。 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. 当您在BlockingCollection<T>上调用Take()时,线程将被阻塞(等待事件句柄),直到元素从另一个线程添加到集合中。 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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM