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?
If you need thread safety use ConcurrentQueue<T>.
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();
        }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With