Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with queue sysmultaneously in different threads

Tags:

c#

.net

How do I work with queue at c#? I want one thread that will enqueue data to the queue & another thread will dequeue data from to the queue. Those threads should run simultaneously.

Is it possible?

like image 391
vrushali Avatar asked May 23 '11 05:05

vrushali


2 Answers

If you need thread safety use ConcurrentQueue<T>.

like image 198
PaulB Avatar answered Sep 21 '22 12:09

PaulB


If you use System.Collections.Queue thread-safety is guaranteed in this way:

var queue = new Queue();
Queue.Synchronized(queue).Enqueue(new WorkItem());
Queue.Synchronized(queue).Enqueue(new WorkItem());
Queue.Synchronized(queue).Clear();

if you wanna use System.Collections.Generic.Queue<T> then create your own wrapper class. I did this allready with System.Collections.Generic.Stack<T>:

using System;
using System.Collections.Generic;

[Serializable]
public class SomeStack
{
    private readonly object stackLock = new object();

    private readonly Stack<WorkItem> stack;

    public ContextStack()
    {
        this.stack = new Stack<WorkItem>();
    }

    public IContext Push(WorkItem context)
    {
        lock (this.stackLock)
        {
            this.stack.Push(context);
        }

        return context;
    }

    public WorkItem Pop()
    {
        lock (this.stackLock)
        {
            return this.stack.Pop();
        }
    }
}
like image 40
benwasd Avatar answered Sep 22 '22 12:09

benwasd