MultiThreading with Generic list


Please briefly explain why you feel this question should be reported .

Report Cancel

I have been using List to store contextual object on a method which is expected to be concurrently accessible. When multiple thread is adding and retrieving message, I was expecting that when object is removed from one thread, the other thread will not get the same message again. This produces issue. Can you suggest me how to solve the problem. I am using C#


in progress 0
C# 1 Answer 5252 views Beginner 2

About the AuthorBeginner

Josh is a software engineer

Answer ( 1 )

  1. abhishek
    abhishek Beginner
    March 5, 2016 at 1:01 pm

    Please briefly explain why you feel this answer should be reported .

    Report Cancel

    Generic lists does not support Multi-threading. But there are some special lists which does inherently supports multi-threading, some of them are :

    1. ConcurrentDictionary
    2. BlockingCollection
    3. ConcurrentQueue

    But if you dont want to use any of them, you can surely go ahead and use lock statements to ensure the thread locking is in place before you add / remove items in a list.

    for instance :

    object obj = new object();

    Here in the above code, we have locked the block when adding and removing an item to and from a list. We have to use an object to consider locking as lock bit is set to an object in heap in case of C#.

Leave an answer