Answer the question
In order to leave comments, you need to log in
Is it possible to lock on a list?
What is the best way to execute lock
So?
// Создали список на уровне класса
private readonly List<T> _inner;
// Лочимся на объект списка
lock (_inner)
{
_inner.Clear();
}
// Создали список на уровне класса
private readonly List<T> _inner;
// Создали объект для блокировки
private readonly object _lock = new object();
// Лочимся на свой объект
lock (_lock)
{
_inner.Clear();
}
Answer the question
In order to leave comments, you need to log in
Let's say _inner
you use it in many places, and there is a certain public method that returns it. Then external code can call this method, get the same instance of the object _inner
, and put its own lock
. So you can accidentally catch a deadlock and hang the application.
Such moments can be very difficult to track down, because the object can be returned indirectly, through an interface, or in some other way. A separate field _lock
is just a rule of good taste, it is created for safety: it is very unlikely that someone would think of using it outside of a statement lock
, much less returning it from a method.
If you have a small code and you are sure that you know what you are doing - there is no difference.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question