C#中Lock使用

C#的Lock确保同一时间只有一个线程能执行关键代码段,防止线程冲突。当其他线程试图进入锁定代码时,它会等待直到对象被释放。应避免锁定公共类型或不受代码控制的实例,最好使用私有对象进行锁定,以保护实例数据。

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

好久没有写了,前段时间写WPF的学习笔记,由于目前换公司了,所以WPF的笔记要延后写了,今天碰到一个关于LOCK的使用问题特记录下来。今天在写一个单例模式的类。

首先定义个接口给其它工程使用的方法:
  public interface ICallService : IO4PubBase
    {
        List GetFundInfo(TGetFundInfoIn paramIn);
    }
然后实现这个接口,这里用到了单例同时也用到了锁:
 public class CallService
    {
        public static ICallService GetInstance()
        {
            return JC_CallService.GetInstance();
        }
    }

    internal class JC_CallService : ICallService
    {
        private static JC_CallService _callServicce;
        private static readonly object _lock = new object();
        private static LSJC_Controller _lsjc_Controller;
        private JC_CallService()
        {
            _lsjc_Controller = LSJC_Controller.GetInstance();
        }

        public static JC_CallService GetInstance()
        {
            if (_callServicce == null)
            {
                lock (_lock)  //有人会用:typeof(JC_CallService)或者this
                {
                    if (_callServicce == null)
                    {
                        _callServicce = new JC_CallService();
                    }
                }
            }
            return _callServicce;
        }

        public List GetFundInfo(TGetFundInfoIn paramIn)
        {
            return _lsjc_Controller.GetFundInfo(paramIn);
        }

        public List GetFundInfoMulti(List paramListIn)
        {
            return _lsjc_Controller.GetFundInfoMulti(paramListIn);
        }
    }
上面肯定很多人那么写并且认为不会有问题,我以前就用过lock(this)然后发生问题了。查阅资料发现了微软的具体解释:

lock ensures that one thread does not enter a critical section of code while another thread is in the critical section. If another thread attempts to enter a locked code, it will wait, block, until the object is released.

The section Threading (C# Programming Guide) discusses threading.

lock calls Enter at the beginning of the block and Exit at the end of the block.

In general, avoid locking on a public type, or instances beyond your code's control. The common constructs lock (this)lock (typeof (MyType)), andlock ("myLock") violate this guideline:

  • lock (this) is a problem if the instance can be accessed publicly.

  • lock (typeof (MyType)) is a problem if MyType is publicly accessible.

  • lock(“myLock”) is a problem since any other code in the process using the same string, will share the same lock.

Best practice is to define a private object to lock on, or a private static object variable to protect data common to all instances.

所以以后使用要切记! 微软资料地址


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值