I have a List and two threads that using the List.
The first thread is getting new connections, each new connection is added to the List.
The second thread looping over the List to handle the connections (using foreach).
The problem is that sometimes while the second thread is looping over the List, the List changes before the loop ends. I even tried creating a new copy of the list and looping over it. But it produces some other problems.
I don’t want to create a new thread to handle each new connection, because I understood that too many threads can hurt performance. Is there any other way to handle the connections?
2 problems.
1) You need locking around the list.
You need to ensure you have mutual exclusive access to the list, so it can’t be enumerated over while it’s modified.
A first solution is to use locks:
More elegantly, you could use one of the new collections in the Concurrent namespace, like BlockingCollection. The latter in not enumeration-safe, but provides a
Take()method that can be used to retrieve objects from it, while producers are inserting them.2) Avoid creating a gazillion threads.
You could use the .NET thread pool to enqueue as many request as you like, and the framework will take care of mapping them onto actual threads, without killing the system.