C # in a multithreaded environment, security traversal operations

Source: Internet
Author: User
Tags mutex

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

Related Article

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.