MultiThreading with Generic list
ReportQuestion
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#
5 years
1 Answer
5185 views
Beginner 2
Answer ( 1 )
Please briefly explain why you feel this answer should be reported .
Report CancelGeneric lists does not support Multi-threading. But there are some special lists which does inherently supports multi-threading, some of them are :
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();
lock(obj){
lst.add(aa);
}
lock(obj){
lst.Remove(aa);
}
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#.