Admdebian
Admdebian

Reputation: 660

C# Queue and Enumerator with 2 threads

I have 2 thread:

Thread A: it puts items in the queue

toDoReuqests.Enqueue(item);

Thread B: it gets items from the queue

var iterator = toDoReuqests.GetEnumerator();
while ( iterator.MoveNext() )
{
    Console.WriteLine("Tolto dalla coda B");
    Console.WriteLine(iterator.Current.id);
}

Is it the correct way to remove items from the queue? Can multithread give me an error on the enumerator?

Upvotes: 0

Views: 69

Answers (2)

Backs
Backs

Reputation: 24903

Yes, you will have problems with 2 threads and simple Queue. Advice - use ConcurrentQueue. It's thread safe.

Thread A:

toDoReuqests.Enqueue("test");

Thread B:

string retValue;

while(!toDoReuqests.TryDequeue(out retValue))
{
    Console.WriteLine("Tolto dalla coda B");
    Console.WriteLine(retValue);    
}

For removing items from queue use methods Dequeue or TryDequeue.

Upvotes: 3

Rob
Rob

Reputation: 27357

Your code will not remove items from the queue, it will simply iterate them. You need to do something like this:

while ( queue.Count > 0 )
{
    var current = queue.Dequeue();
    Console.WriteLine("Tolto dalla coda B");
    Console.WriteLine(current);
}

Also, the code is not thread-safe, you'll either need a thread-safe implementation of queue, or guard it with locks

Upvotes: 1

Related Questions