How to properly lock access to a List in multiple Threads


I have a List that I am adding values to, every interval seconds, which is running in a thread.
var point = GetPoint(presentValue);
DataSource[itemIndex].Add(point);
In an Event I then read values from that List, to be exact I search for the closest value to my target. I Create a local variable for that list to work with, but sometimes I get the Exception
"Destination array not long enough" when creating this List.
I've figured out that this must mean the List was changed while the new List was created, so it's got something to do with the Code above. After a bit of research I found about thread-safety and the "lock" keyword, which I then tried to use. I tried locking to the list itself, to the list's SyncRoot and to a custom sync object, but the error still occured.

lock (SyncHelper.TrendDataPointLock)
{
    var point = GetPoint(presentValue);
    DataSource[itemIndex].Add(point);
}
and
lock (SyncHelper.TrendDataPointLock)
{
    points = new List<DataPoint>(ActualPoints);
}
I know that I'm not fully familiar with the aspects of thread safety, but after looking at many different approaches I still can't seem to make this work.
1: Any advice on how to fix my error
2: Do I need to have a lock statement on every access of that list in order to be sure that the thread will pause before the other lock is released?
3: If not 2, then does locking to the list itself, make every thread block, no matter if they also have a lock statement around the list access or not? So locking on the Add statement "should" fix my problem.
  • You should use a lock() every time you use the List to ensure that it is thread safe. You can create an object that you use for locking. Use this object only and on every occasion: private object lockObject = new object();. When locking: lock(lockObject) { ... } – Stefan 32 mins ago 

Your Answer

Post a Comment

0 Comments