您的位置:首页 > 编程语言 > C#

C#中Lock使用

2014-03-14 21:40 92 查看
好久没有写了,前段时间写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
public type,
or instances beyond your code's control. The common
constructs 
lock
(this)
lock (typeof
(MyType))
, and
lock
("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
private object
to lock on, or a private
static
 object variable to protect data
common to all instances.

所以以后使用要切记! 微软资料地址
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: