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

View: 17802|Reply: 0

[Communication] lock C #

[Copy link]
Posted on 2/21/2019 9:43:39 AM | | |
1. Why lock and what is locked?

When we use threads, the most efficient way is of course asynchronous, that is, each thread runs at the same time, without relying on each other and waiting. However, when different threads need to access a certain resource, a synchronization mechanism is required, that is, when reading and writing the same resource, we need to make the resource only operated by one thread at the same time to ensure that each operation is effective and immediate, that is, to ensure the atomicity of its operation. lock is the most commonly used synchronization method in C#, in the format lock(objectA){codeB}.


lock(objectA){codeB} seems simple, but it actually has three meanings, which is essential for using it appropriately:
1. Is objectA locked? If not, I'll lock it, otherwise wait until objectA is released.
2. After locking, other threads cannot call codeB or use objectA during the execution of codeB.
3. After executing codeB, release objectA, and codeB can be accessed by other threads.

2. What happened to lock(this)?

Let's look at an example:

In the t1 thread, LockMe calls lock(this), that is, c1 in the main function, and when calling lock(c1) in the main thread, it must wait for the lock block in t1 to be executed before accessing c1, that is, all c1-related operations cannot be completed, so we see that even c1. DoNotLockMe() is not executed.





Previous:C# in ArraySegment part of the array
Next:In-depth practice of Spring Boot. Chen Shaojian and SpringBoot reveal + quickly build a microservice system
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