c# Lock Thread

本文介绍C#中Lock关键字的使用方法及其注意事项,解释如何通过锁来实现线程间的同步,避免竞态条件,并给出一个账户余额操作的实例。此外,还展示了如何创建线程及设置前台与后台线程的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Lock : 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁。此语句的形式如下:
    Object thisLock = new Object();
    lock (thisLock)
    {
    // Critical code section
    }
    给定的对象设置锁

  2. Lock : 确保当一个线程位于代码的临界区时,另一个线程不进入临界区。如果其他线程试图进入锁定的代码,则它将一直等待(即被阻止),直到该对象被释放。
    lock 调用块开始位置的 Enter 和块结束位置的 Exit。
    通常,应避免锁定 public 类型,否则实例将超出代码的控制范围。常见的结构 lock (this)、lock (typeof (MyType)) 和 lock (“myLock”) 违反此准则:
    ● 如果实例可以被公共访问,将出现 lock (this) 问题。
    ● 如果 MyType 可以被公共访问,将出现 lock (typeof (MyType)) 问题。
    ● 由于进程中使用同一字符串的任何其他代码将共享同一个锁,所以出现 lock(“myLock”) 问题。
    最佳做法是定义 private 对象来锁定, 或 private static 对象变量来保护所有实例所共有的数据。

创建一个简单线程
using System;
using System.Threading;

class ThreadTest
{
public void RunMe()
{
Console.WriteLine(“RunMe called”);
}

static void Main()
{
    ThreadTest b = new ThreadTest();
    Thread t = new Thread(b.RunMe);
    t.Start();
}

}

下面是一个 例子,如果是 想要把 Lock 去掉, 那就得保证 下面只执行一次,否则他们是同步的,随时都会访问上一次的对象。

   for (int i = 0; i < 10; i++)
        {
            threads[i].Start();
        }

具体代码如下

using System;
using System.Threading;

class Account
{
    private Object thisLock = new Object();
    int balance;

    Random r = new Random();

    public Account(int initial)
    {
        balance = initial;
    }

    int Withdraw(int amount)
    {

        // This condition will never be true unless the lock statement
        // is commented out:
        if (balance < 0)
        {
            throw new Exception("Negative Balance");
        }

        // Comment out the next line to see the effect of leaving out 
        // the lock keyword:
        lock(thisLock)
        {
            if (balance >= amount)
            {
                Console.WriteLine("Balance before Withdrawal :  " + balance);
                Console.WriteLine("Amount to Withdraw        : -" + amount);
                balance = balance - amount;
                Console.WriteLine("Balance after Withdrawal  :  " + balance);
                return amount;
            }
            else
            {
                return 0; // transaction rejected
            }
        }
    }

    public void DoTransactions()
    {
        for (int i = 0; i < 100; i++)
        {
            Withdraw(r.Next(1, 100));
        }
    }
}

class Test
{
    static void Main()
    {
        Thread[] threads = new Thread[10];
        Account acc = new Account(1000);
        for (int i = 0; i < 10; i++)
        {
            Thread t = new Thread(new ThreadStart(acc.DoTransactions));
            threads[i] = t;
        }
        for (int i = 0; i < 10; i++)
        {
            threads[i].Start();
        }
    }
}

线程 : 分为 前台,后台,
前台 : Main退出的时候,就依然运行。
后台 : Main退出的时候,也结束。

    static void Main(string[] args)
    {
        Thread obj1 = new Thread(Function1);
        obj1.IsBackground = true;
        obj1.Start();


        Console.WriteLine("There is a Constrol");
    }

    static void Function1()
    {
        Console.WriteLine("The Enter");
        Console.ReadLine();
    Console.WriteLine("The Exit");
    }

    static void Function2()
    {
        Console.WriteLine("Function The Enter");

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值