0

I was working on a project written in C# where I had couple of collections that would be accessed and modified by different threads/tasks, therefore I used the lock keyword(quite a lot). I followed the notes mentioned here and other references/tutorials available online to utilize this keyword properly. At the exam, I was asked how I could avoid these explicit locks. Thanks in advance and I hope this question is proper to be asked here.

Here is some code sample(there are other loops and method calls as well, I deleted them to have a shorter sample) :

            try
        {
            lock (this)
            {
                if (!IsReplaying)
                {
                                        //removing igonored tracks from bufferlist 
                    for (int i = 0; i < BufferList.Count; i++)
                    {
                        for (int j = 0; j < ListOfIgnoredTracks.Count; j++)
                        {
                            CAT62Data dataitem = BufferList[i];
                            if (BufferList[i].CAT62DataItems[10].value != null)
                            {
                                if (BufferList[i].CAT62DataItems[10] != null && BufferList[i].CAT62DataItems[10].value != null)
                                {
                                    if (dataitem.CAT62DataItems[10].value.ToString() == ListOfIgnoredTracks[j].CAT62DataItems[10].value.ToString() && !dataitem.IsModified && !dataitem.IsUserAdded)
                                    {
                                        BufferList.RemoveAt(i--);
                                    }
                                }
                            }
                        }
                    }

                    BufferList.Clear();

                    RemoveLostTracks(new DateTime());
                }
            }
        }
Community
  • 1
  • 1
arvind
  • 189
  • 3
  • 19

1 Answers1

1

One of the answers, you can use instead of your standard collections this namespace.

System.Collections.Concurrent

Here you will find the same collections, which are Thread Safe. so you don't need to write lock anymore.

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • I actually looked at it but based on this [link](http://stackoverflow.com/questions/6601611/no-concurrentlistt-in-net-4-0) it is not acting asynchronously. – arvind Apr 06 '16 at 08:24
  • @arvind. These collections are used when many threads try to add elements or remove elemets from that collections.So that threads don't prevent each other,they use this collections – Suren Srapyan Apr 06 '16 at 08:52