157 suggestions for writing high-quality code to improve the C # Program-Recommendation 22: ensure the thread security of the set,

Source: Internet
Author: User

157 suggestions for writing high-quality code to improve the C # Program-Recommendation 22: ensure the thread security of the set,

Recommendation 22: Ensure the thread security of the Set

Thread security means that when elements are added or deleted on multiple threads, the thread keys must be synchronized.

The following code simulates the deletion of elements by a thread during iteration.

Class Program {static List <Person> list = new List <Person> () {new Person () {Name = "Rose", Age = 19}, new Person () {Name = "Steve", Age = 45}, new Person () {Name = "Jessica", Age = 20},}; static AutoResetEvent autoSet = new AutoResetEvent (false ); static void Main (string [] args) {Thread t1 = new Thread () => {// ensure that the following code autoSet is run only after t2 starts. waitOne (); foreach (var item in list) {Console. writeLine ("t1:" + item. name); Thread. sleep (1000) ;}}); t1.Start (); Thread t2 = new Thread () =>{// notification t1 can execute code autoSet. set (); // sleeping for 1 second is to ensure that the delete operation is in the iteration process of t1 Thread. sleep (1000); list. removeAt (2) ;}); t2.Start () ;}} class Person {public string Name {get; set ;}public int Age {get; set ;}}

The above code will throw InvalidOperationException: "The set has been modified and enumeration may not be executed ."

Before the occurrence of a generic set, a non-generic set generally provides a SyncRoot attribute. To ensure the thread security of a non-generic set, you can lock this attribute. If the preceding set is replaced by ArrayList, lock should be added during iteration and deletion to ensure thread security. The Code is as follows:

Static ArrayList list = new ArrayList () {new Person () {Name = "Rose", Age = 19}, new Person () {Name = "Steve ", age = 45}, new Person () {Name = "Jessica", Age = 20},}; static AutoResetEvent autoSet = new AutoResetEvent (false ); static void Main (string [] args) {Thread t1 = new Thread () => {// ensure that the following code autoSet is run only after t2 starts. waitOne (); lock (list. syncRoot) {foreach (Person item in list) {Console. writeLine ("t1:" + item. name); Thread. sleep (1000) ;}}); t1.Start (); Thread t2 = new Thread () =>{// notification t1 can execute code autoSet. set (); // sleeping for 1 second is to ensure that the delete operation is in the iteration process of t1 Thread. sleep (1000); lock (list. syncRoot) {list. removeAt (2); Console. writeLine ("deleted successfully") ;}}); t2.Start ();}

The above code will not throw an exception, because the lock ensures that only one thread can operate on the collection element at a time through the mutex mechanism. We can find that the generic set does not have such an attribute. You must create a locked object to complete the synchronization task. You can lock a new static object by using the following code:

Static List <Person> list = new List <Person> () {new Person () {Name = "Rose", Age = 19}, new Person () {Name = "Steve", Age = 45}, new Person () {Name = "Jessica", Age = 20},}; static AutoResetEvent autoSet = new AutoResetEvent (false ); static object sycObj = new object (); static void Main (string [] args) {// object sycObj = new object (); Thread t1 = new Thread (() ==>{ // ensure that the following code autoSet is run only after t2 starts. waitOne (); lock (sycObj) {foreach (Person item in list) {Console. writeLine ("t1:" + item. name); Thread. sleep (1000) ;}}); t1.Start (); Thread t2 = new Thread () =>{// notification t1 can execute code autoSet. set (); // sleeping for 1 second is to ensure that the delete operation is in the iteration process of t1 Thread. sleep (1000); lock (sycObj) {list. removeAt (2); Console. writeLine ("deleted successfully") ;}}); t2.Start ();}

 

 

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.