Using the same lock for multiple methods

前端 未结 5 1711
时光说笑
时光说笑 2021-01-01 13:07

I haven\'t had any issues using the same lock for multiple methods so far, but I\'m wondering if the following code might actually have issues (performance?) that I\'m not a

5条回答
  •  自闭症患者
    2021-01-01 13:47

    If the methods are unrelated as you state, then use a different lock for each one; otherwise it's inefficient (since there's no reason for different methods to lock on the same object, as they could safely execute concurrently).

    Also, it seems that these are instance methods locking on a static object -- was that intended? I have a feeling that's a bug; instance methods should (usually) only lock on instance fields.

    Regarding the Singleton design pattern:

    While locking can be safe for those, better practice is doing a delayed initialization of a field like this:

    private static object sharedInstance;
    public static object SharedInstance
    {
         get
         {
              if (sharedInstance == null)
                  Interlocked.CompareExchange(ref sharedInstance, new object(), null);
              return sharedInstance;
         }
    }
    

    This way it's a little bit faster (both because interlocked methods are faster, and because the initialization is delayed), but still thread-safe.

提交回复
热议问题