This article takes list as the object of action
MSDN official gives a list of thread-safe sayings:
public static members of this type are thread-safe. However, there is no guarantee that any instance members are thread-safe.
The List can support multiple readers at the same time, as long as the collection is not modified. Enumerating through collections is inherently not a thread-safe process. In rare cases where an enumeration competes with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow multiple threads to access the collection for read and write operations, you must implement your own synchronization.
What if I don't synchronize?
If a thread performs a delete operation, and a thread iterates, the collection is modified during the traversal, causing the InvalidOperationException exception to occur, prompting that the collection has been modified and the enumeration operation may not be performed.
How to synchronize to ensure the security of traversal
The critical section, the mutex, is used to secure the thread traversal process, as shown in the following example code:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Threading;4 5 namespaceConsoleApp6 {7 class Program8 {9 Public Staticlist<string> SimpleList =Newlist<string>();Ten One Public Static voidMain (string[] args) A { - //critical Section Object - ObjectLockobj =New Object(); the - //to add test data to the list - string[] data = {"1","2","3","4","5","6","7","8" }; - simplelist.addrange (data); + //This thread is used to iterate over an array - NewThread (NewThreadStart (() = + { A //used for synchronization, enter the critical section, only after traversing, releasing the mutex of the critical section object, in order to write operations at Lock(lockobj) - { - foreach(varIteminchSimpleList) - { - Console.WriteLine (item); -Thread.Sleep ( -); in } - } to })). Start (); + //This thread performs a delete operation - NewThread (NewThreadStart (() = the { * Lock(lockobj) $ {Panax NotoginsengSimplelist.removeat (0); -Console.WriteLine ("RM 1"); theThread.Sleep ( -); +Simplelist.removeat (0); AConsole.WriteLine ("RM 2"); the } + })). Start (); - $ console.readline (); $ } - } -}
C # in a multithreaded environment, security traversal operations