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

View: 30344|Reply: 2

[Source] C# thread safety with lock

[Copy link]
Posted on 6/13/2016 5:26:25 PM | | |

If your code is in a process that has multiple threads running at the same time, it may be running the code at the same time. If the result of each run is the same as that of a single thread, and the values of other variables are the same as expected, it is thread safe.
In other words, the interface provided by a class or program is atomic for threads or switching between multiple threads does not lead to ambiguity in the execution result of the interface, which means that we do not need to consider synchronization.
Thread safety issues are caused by both global and static variables.
If each thread only has read operations for global variables and static variables, but no write operations, generally speaking, this global variable is thread-safe; If multiple threads perform read and write operations on a variable at the same time, thread synchronization is generally required, otherwise it may affect thread security.

The purpose of lock is to prevent concurrent operations when multi-threaded execution, and objects of the reference type of lock allow only one thread to operate at a time in its locked area.

lock can only lock one reference type variable, that is, lock an address




There is a difference between the results of running with and without locking:

After locking: the value of i will decrease one by one, there will be no jumps, no repeated output, until the value of 0;

No lock: the value output of i will jump, discontinuous decreasing, and may also have a -1 value output;

Reason: After adding a lock, only one thread can execute the code in the locked area at a time, and both threads are executed in order, so there will be no interrupted output.




Previous:User cancelled out of save dialogue (MS Visual Database Tools)
Next:A nice DBHelper class that executes stored procedures
Posted on 6/14/2016 10:53:36 AM |
 Landlord| Posted on 2/10/2022 9:18:58 AM |
.NET/C# Lock Principle Monitor provides an in-depth explanation
https://www.itsvse.com/thread-9633-1-1.html
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