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

前端 未结 5 1988
南旧
南旧 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

    It seems clear to me that using a lock(...) {...} lock is the right answer.

    To guarantee the thread safety of the Queue, all operations must be done through this wrapper only.

    If other threads access the queue without using .Synchronized(), then you'll be up a creek - unless all your queue access is locked up.

提交回复
热议问题