[C#] Lock code block of Lock in knowledge point practice sequence

Hello everyone, I am Full Stack Xiao5. Welcome to the article "Practice Sequence of Knowledge Points in Xiao5 Lecture Hall".
The first article in 2024. This article is the Lock knowledge point in the practical sequence of C# knowledge points. The blogger's ability and understanding level are limited. If there is anything wrong, please correct me!
This article verifies the execution of the Lock code, the code execution of the upper and lower codes outside the lock and the lock area.

Insert image description here

Insert image description here

basic concept

In C#, lock is a mechanism used to achieve multi-thread synchronization.
It can be used to ensure that only one thread can access a locked block of code at any given time to avoid data races and concurrent access issues.

  • flow chart
    Insert image description here

lock process

1. Create a shared resource that needs to be accessed safely between multiple threads.
2. Use lockthe keyword to define a critical area (that is, the code segment that needs to be synchronized), and place the code that needs to access shared resources in the critical area.
3. Before entering the critical area, the thread will try to acquire the lock. If the lock is already held by another thread, the current thread blocks until the lock is released.
4. When a thread obtains the lock, it can safely access the code in the critical area and release the lock after completion so that other threads can continue execution.

important point

1. The locked object should be a shared object that can be accessed by all threads. A common practice is to use a private variable as the lock object.
2. The scope of the lock should be as small as possible, and only the necessary code areas should be locked to avoid unnecessary thread blocking.
3. The use of locks should follow a consistent principle, that is, the same lock object must be used in all places where shared resources are accessed. This ensures that all threads acquire locks in order and avoids deadlock.

Practical scenario

Verify the basic concepts of knowledge points through actual examples, which can deepen your understanding of knowledge points. Only by understanding the knowledge points deeply enough can you better write high-quality code and implement efficient logic code.

Lock code block

The following shows that the code block is locked, but other code within the method is still executed directly in sequence.
For example, if you click the three buttons of user a, user b, and user c at the same time, the same method will be called. Only the statistical quantity is locked in the method, and it is locked for 3 seconds. Other codes are not locked.

Effect

From the following interface effect, we can know that the code that is not locked will be executed first, and then the locked area will be executed first for user a, and then after 3 seconds of locking, user b will be executed, and so on.
Insert image description here

code

namespace XxxData
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();

            CheckForIllegalCrossThreadCalls = false;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
    
    

        }

        private int visitorCount = 0;
        private void TargetData(string user)
        {
    
    
            txtInfo.AppendText($"{
      
      user}{
      
      DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")}\r\n");

            lock (this)
            {
    
    
                visitorCount += 1;
                lbVisitorCount.Text = $"访问用户数:{
      
      visitorCount}";

                Thread.Sleep(3 * 1000);
                txtInfo.AppendText($"{
      
      user}执行完毕,{
      
      DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss")}\r\n");
            }
        }

        private void btnA_Click(object sender, EventArgs e)
        {
    
    
            Task.Run(() =>
            {
    
    
                TargetData("用户a");
            });
        }

        private void btnB_Click(object sender, EventArgs e)
        {
    
    
            Task.Run(() =>
            {
    
    
                TargetData("用户b");
            });
        }

        private void btnC_Click(object sender, EventArgs e)
        {
    
    
            Task.Run(() =>
            {
    
    
                TargetData("用户c");
            });
        }
    }
}

FAQ

message queue

Whether the Lock code block belongs to a message queue, multiple accesses come in at the same time, and only one access can be queued. A will only allow the next execution to come in after executing the code in the Lock method.

No, the lock keyword in C# is not a message queue. It is a thread synchronization mechanism used to ensure that only one thread can enter the locked code block at the same time when multiple threads access shared resources.
When multiple threads access the area containing the lock code block at the same time, only one thread can obtain the lock and enter the critical area to execute the code, while the remaining threads are blocked and queued to wait for the lock to be released. Once the thread that acquired the lock completes execution and releases the lock, the next thread in the waiting queue acquires the lock, and so on.
This mechanism ensures that only one thread can access shared resources at the same time, avoiding data competition and concurrent access problems. But please note that the lock does not provide a sequence guarantee, that is, it does not guarantee that the threads in the waiting queue will acquire the lock in a specific order.
Message queues are another mechanism used for communication between threads (or processes). It allows messages to be sent from one thread to another thread, and the receiving thread can process the messages in the order of the messages, realizing asynchronous communication and task distribution. The lock keyword only provides the ability of mutually exclusive access and does not involve the sending and receiving of messages.

Common errors

##Cross-thread access
Since the label control is in the main thread, it is inaccessible by default in the Task thread Insert image description here
. To solve the problem, add the following code in front of the asynchronous method.

CheckForIllegalCrossThreadCalls = false;

Summary: Review the past and learn the new. Reviewing knowledge points at different stages will lead to different understandings and understandings. The blogger will consolidate the knowledge points and share them with everyone in a practical way. If it can be helpful and gainful, this will be a blog post. The Lord’s greatest creative motivation and honor. I also look forward to meeting more outstanding new and old bloggers.

Guess you like

Origin blog.csdn.net/lmy_520/article/details/135315235