SoFunction
Updated on 2025-03-09

Describe the use of lock keywords in C# multithreading


using System;
using ;
namespace ThreadSimple
{
    internal class Account
    {
int balance; //Balance
        Random r=new Random();
        internal Account(int initial) 
        { 
            balance=initial;
        }
internal int Withdraw(int amount) //Retrieve and withdraw money
        {
            if(balance<0)
            { 
// If balance is less than 0, an exception will be thrown
throw new Exception("NegativeBalance");//Negative balance
            }
//The following code ensures that the current thread will complete the balance value
//No other threads will execute this code to modify the balance value.
// Therefore, the value of balance cannot be less than 0
            lock(this) 
            {
                ("CurrentThread:"+);
//If there is no protection of the lock keyword, it may be after the conditional judgment of if (established) is executed.
//Another thread executes balance=balance-amount to modify the balance value
//This modification is invisible to this thread, so it may cause the if condition to be invalid at this time.
//However, this thread continues to execute balance=balance-amount, so the balance may be less than 0
                if(balance>=amount)
                {
                    (5);
                    balance=balance-amount;
                    return  amount;
                }  else
                {
                    return 0;
                    //transactionrejected
                }
            } 
        }
internal void DoTransactions()// Withdrawal transactions
        {
            for (int i = 0; i < 100; i++)
            {
                Withdraw((-50, 100));
            }
        }
    }  
    internal class Test 
    { 
        static internal Thread[] threads=new Thread[10];
        public static void Main() 
        { 
            Account acc=new Account(0);
            for(int i=0;i<10;i++)
            { 
                Thread t=new Thread(new ThreadStart());
                threads[i]=t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Name = ();
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
                ();
            }
        }
    }
}