is asynchronous and parallel ~list<t> thread-safe?

Source: Internet
Author: User

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?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.