Share via


Consider Creating a new class for locking

C# provides keyword lock for synchronized access.

A good practice is to create a private object for locking purpose. For example,

public class LockExample

{

    private object syncObject = new object();

    public void SynchronizedMethod()

    {

        lock (syncObject)

        {

        }

}
}

It may make sense to create a class just for locking purpose:

using System;

class LockClass : object { };

public class LockExample

{

    private object syncObject = new LockClass();

    public void SynchronizedMethod()

    {

        lock (syncObject)

        {

        }

    }

}

The advantage of the second approach, is that you can easily tell how many lock objects you have used in your project using SOS command “!dumpheap -mt”.

Comments

  • Anonymous
    April 14, 2008
    PingBack from http://microsoftnews.askpcdoc.com/?p=2298

  • Anonymous
    April 15, 2008
    Back when the D programming language was about to hit V1.0 I was arguing that this should be mandated by the platform. There should be a System.Lock type which is the only thing that you can lock on. There are heaps of advantages and not too many disadvantages:

  1. Shave 4 (or 8) bytes off every object instance, since there is no need for a sync block.
  2. Fewer stupid locking mistakes in code, including locking (this) when you shouldn't be, or locking on public objects.
  3. Diagnostics. If the CLR supported this intrinsically you could conceivably name your locks and get great diagnostics about which thread holds what locks, which threads are waiting on what objects etcetera. I'm sure there are some things I'm missing here, but you get the idea. Restricting flexibility can often bring big wins. Oh well, too late for change I guess.
  • Anonymous
    April 15, 2008
    Can't you just accomplish the same thing by using the !syncblk command?

  • Anonymous
    April 15, 2008
    .NET The empty try block mystery IoC Container Benchmark - Unity, Windsor, StructureMap and Spring.NET

  • Anonymous
    April 26, 2008
    I never thought of using classes instead of locks to make it easy to use with SOS. Thanks for the idea. I have used a separate class to do locking; the reason was so I could easily vary the lock strategy (e.g. Monitor versus Reader-Writer). There are other uses too: app-wide bookkeeping, naming, home-grown priority inversion control, deadlock detection, etc.