从C#中的ConcurrentQueue出队的对象对象、ConcurrentQueue

2023-09-03 02:37:56 作者:后会可期

嘿,我想实现在C#中ConcurrentQueue一个异步服务器。项目被尽快接收到完整的消息排队。要出队的消息,我正在做一个小数目的线程办出队和维修要求的工作。这是不够的,因为每个线程使用一个while循环,消耗相当大量的处理器时间,原因是显而易见的。

请问有谁知道在需要时出队的消息,但不消耗那么多的处理时间的方法。

  {
    ...

    的for(int i = 0;我3;;我++)
    {
        线程t =新主题(新的ThreadStart(startParsingMessages));
        t.Start();
    }

    ...
}

私人无效startParsingMessages()
{
    QueueContainer出列= NULL;
    Console.WriteLine(尝试);
    而(真)
    {
        如果(queue.TryDequeue(出出队))
        {
            Console.WriteLine(处理队列);
            ProcessMessage的(dequeued.socket,dequeued.message);
        }
    }
}
 

解决方案

而不是使用 ConcurrentQueue< T> 直接,你有没有试过包装在一个 BlockingCollection< T> ?然后你可以使用 TryTake(出T,时间跨度)等,我相信这是预期用途:该并发集合本身就的一般的在那里只是这样你就可以选择阻止收集是如何工作的。

这并不一定是的只有的使用了这些藏品,当然,但特别是对 ConcurrentQueue< T> ,生产者/消费者排队情况是最常见的一种 - 在这一点 BlockingCollection< T> 是可以很容易地做正确的事的方式

用并发队列 ConcurrentQueue 实现多线程任务中随时异步回调进度通知 .Net4.0

Hey, I'm trying to implement a ConcurrentQueue in C# for an asynchronous server. Items are being queued as soon as a complete message is received. To dequeue messages, I'm making a small number of threads to do the work of dequeueing and servicing the requests. This is inadequate as each thread is using a while loop, which consumes rather a large amount of processor time, for obvious reasons.

Would anyone know of a method of dequeueing messages when required but not consuming so much processing time.

{
    ...

    for (int i = 0; i < 3; i++)
    {
        Thread t = new Thread(new ThreadStart(startParsingMessages));
        t.Start();
    }

    ...
}

private void startParsingMessages()
{
    QueueContainer dequeued = null;
    Console.WriteLine("Trying");
    while (true)
    {
        if (queue.TryDequeue(out dequeued))
        {
            Console.WriteLine("processing queue");
            ProcessMessage(dequeued.socket, dequeued.message);
        }
    }
}

解决方案

Instead of using ConcurrentQueue<T> directly, have you tried wrapping it in a BlockingCollection<T>? Then you can use TryTake(out T, TimeSpan) etc. I believe that's the expected use: that the concurrent collections themselves would usually be there just so you can select how the blocking collection will work.

That doesn't have to be the only use for these collections of course, but particularly for ConcurrentQueue<T>, the producer/consumer queue scenario is the most common one - at which point BlockingCollection<T> is the way to make it easy to do the right thing.