This article is a mirror article of machine translation, please click here to jump to the original article.

View: 19029|Reply: 0

[Source] C# performs secure traversal operations in a multi-threaded environment

[Copy link]
Posted on 10/18/2016 1:55:48 PM | | |

This article uses List as the operation object
MSDN officially gives the thread safety statement of List:
This type of public static member is thread-safe. However, no instance member can be guaranteed to be thread-safe.
As long as the collection is not modified, List can support multiple readers at the same time. Enumerating through a set is not inherently a thread-safe process. In the rare case that an enumeration competes with one or more write accesses, the only way to keep threads safe is to lock the collection for the entire duration of the enumeration. To allow multiple threads to access the collection for read and write operations, you must implement your own synchronization.
If you don't sync?
If one thread performs a deletion operation and a thread performs a traversal operation, then during the traversal process, the collection is modified, which will cause an InvalidOperationException exception to appear, prompting: the collection has been modified; Enumeration operations may not be performed.
How to synchronize to ensure the security of traversal
Critical zones, mutexes are used here to secure the thread traversal process, the example code is as follows:






Previous:Solution to the jssdk signature error of WeChat official account under China Unicom
Next:asp.net MVC global exception handling and exception logs
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com