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

前端 未结 5 1987
南旧
南旧 2020-12-08 09:33

I have a Queue object that I need to ensure is thread-safe. Would it be better to use a lock object like this:

lock(myLockObject)
{
//do stuff with the queue         


        
5条回答
  •  自闭症患者
    2020-12-08 10:00

    There's frequently a tension between demands for 'thread safe collections' and the requirement to perform multiple operations on the collection in an atomic fashion.

    So Synchronized() gives you a collection which won't smash itself up if multiple threads add items to it simultaneously, but it doesn't magically give you a collection that knows that during an enumeration, nobody else must touch it.

    As well as enumeration, common operations like "is this item already in the queue? No, then I'll add it" also require synchronisation which is wider than just the queue.

提交回复
热议问题