M
M
Michael2016-11-02 10:23:30
.NET
Michael, 2016-11-02 10:23:30

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();
}

Or so?
// Создали список на уровне класса
private readonly List<T> _inner;

// Создали объект для блокировки
private readonly object _lock = new object();

// Лочимся на свой объект
lock (_lock)
{
    _inner.Clear();
}

If the second option, then why? Why is lock on the list itself bad and what is the difference? Why create your own object in this case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrew, 2016-11-02
@Sing303

Let's say _inneryou 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 _lockis 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.

M
MIsternik, 2016-11-06
@MIsternik

Why not use ConcurrentBag ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question