Back to Catalog
The topic is a bit of a meaning, everyone knows dictionary<k,v> is not a thread-safe type, and list<t> is thread-safe? Before today, the uncle did not go to test, and today is also a VIP asked me, said in my code used in parallel, and then for a list assignment, said the direct point is: The list element is global, in each line thread to operate it separately, the test data is 10,000, and after the test results, I developed the list element of the final array is more than 9,000, that is, the concurrency of thousands of data, hehe, let's look at the source code!
Test code:
[TestMethod] Public voidTestMethod0 () {List<int> intlist =Newlist<int>(); varresult = 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 results of the unit test, the uncle has always liked this sentence: the machine can prove everything!
As we can see, the length of the array is not 10,000, and some arrays are missing, this is concurrency, this is the thread is unsafe!
Below you will use the encapsulated Concurrentlist thread-safe object and test it again:
[TestMethod] Public voidTestMethod1 () {concurrentlist<int> intlist =Newconcurrentlist<int>(); varresult = Parallel.ForEach (Enumerable.range (1,10000), (val) = ={Intlist.add (val); }); if(result.) iscompleted) {Console.WriteLine ("Intlist.count ():"+intlist.count); } }
Take a look at the results of the test, which is the same as the original 10,000 data
For thread-safe types, multithreading concurrently accesses the list element while other threads are locked, guaranteeing the security of the list object and guaranteeing the correctness of the result.
Back to Catalog
is asynchronous and parallel ~list<t> thread-safe?