In C# would it be better to use Queue.Synchronized or lock() for thread safety?

Personally I always prefer locking. It means that you get to decide the granularity. If you just rely on the Synchronized wrapper, each individual operation is synchronized but if you ever need to do more than one thing (e.g. iterating over the whole collection) you need to lock anyway. In the interests of simplicity, I prefer to just have one thing to remember – lock appropriately!

EDIT: As noted in comments, if you can use higher level abstractions, that’s great. And if you do use locking, be careful with it – document what you expect to be locked where, and acquire/release locks for as short a period as possible (more for correctness than performance). Avoid calling into unknown code while holding a lock, avoid nested locks etc.

In .NET 4 there’s a lot more support for higher-level abstractions (including lock-free code). Either way, I still wouldn’t recommend using the synchronized wrappers.

Leave a Comment