c# Mutex or lock() {}

etienne_marais

Honorary Master
Joined
Mar 16, 2008
Messages
16,250
Reaction score
19,740
Location
Centurion
I have a foreach loop that calls MyQueue.Deque() within the loop, it runs in a thread.

A different thread (with completely different function) can add to the Queue, thus modifying the collection which c# does not like when iterating over foreach (and rightly so).

If there is a 'clash' then I get an exception. Rare, but happens from time to time.

Is lock(MyQueue) over the foreachloop as well as the MyQueue.Enqueue(...) adequate or do I have to consider Mutex or perhaps something else ?

My understanding is that lock(...) {...} has more to do with protecting critical sections in code than actually locking the relevant object from access by ANY other ? Or is this not the case. I know Mutex can be program-wide (or even computer-wide).
 
Last edited:
What type of .net object is MyQueue?
 
Admin, please move to dev. section.

What type of .net object is MyQueue?
I have various Queues, these are all System.Collections.Generic.Queue which are either taking the default 'object ' as collection type or some cases 'strongly' Typed like
Queue<SqlCommand>
 
Admin, please move to dev. section.


I have various Queues, these are all System.Collections.Generic.Queue either taking object or some cases Typed like
Queue<SqlCommand>
If using threads you should use specific objects designed for for parallelism/threads. I think for queue the object is ConcurrentQueue in System.Collections.Concurrent
 
Apologies, the foreach loop does not enque, it just uses a stringbuilder to report on all objects in the queue.
 
My understanding is that lock(...) {...} has more to do with protecting critical sections in code than actually locking the relevant object from access by ANY other ? Or is this not the case. I know Mutex can be program-wide (or even computer-wide).
For locking try using the Monitor.TryEnter instead of lock. Should be simpler.
 
Concurrent data structures as has been said here. Mutex, etc. fully lock a thread and then the thread is left in a suspended state until the mutex is released.
A concurrent data structure can lock parts of the data in use, meaning it is likely not to lock, especially for something like a linked data structure such as FILO.
Not to mention that concurrent data structures can actually use atomics which are significantly more performant.

Overall using locks on classic data structures is, to me, a huge no-no when I do CRs, unless there is interaction across multiple pieces of data requiring synchronisation across all parts simultaneously
 
Top
Sign up to the MyBroadband newsletter
X