Asynchronous and parallel ~ List <T> is it thread-Safe ?, Asynchronous list
Returned directory
The question is a bit interesting. We all know that Dictionary <K, V> is not a thread-safe type, and List <T> is thread-safe? Today, my Uncle hasn't tested it before, but today I am also asked by a VIP, saying that parallel is used in my code, and then assigned a value to a List, the direct point is that the List element is global and operated separately in each thread. the test data is 10 thousand records, and after the test result, the final array of the List element I developed is more than 9000, that is, thousands of data records are concurrently processed. Let's take a look at the source code!
Test code:
[TestMethod] public void TestMethod0() { List<int> intList = new List<int>(); var result = Parallel.ForEach(Enumerable.Range(1, 10000), (val) => { intList.Add(val); }); if (result.IsCompleted) { Console.WriteLine("intList.Count():" + intList.Count); } }
Let's take a look at the unit test results. Uncle has always liked this sentence: The machine can prove everything!
We can see that the length of the array is not 10 thousand, but some arrays are lost. This is concurrency, which is the thread's insecurity!
Next we will use the encapsulated ConcurrentList thread-safe object, and then perform a test:
[TestMethod] public void TestMethod1() { ConcurrentList<int> intList = new ConcurrentList<int>(); var result = Parallel.ForEach(Enumerable.Range(1, 10000), (val) => { intList.Add(val); }); if (result.IsCompleted) { Console.WriteLine("intList.Count():" + intList.Count); } }
Let's take a look at the test result. It is the same as the original 10 thousand pieces of data.
For the thread-safe type, when multiple threads concurrently access the List element, other threads are locked to ensure the security of the List object and the correctness of the results.
Returned directory