简体   繁体   中英

C# equivalent of Java's synchronized (abc.class)

I would like to know if there is C# equivalent of the following Java code:

synchronized (abc.class) {
   // code here
}

If there isn't an equivalent, then how can I simulate it in C#?

  • abc is a one of my classes in the program.
  • abc properties and methods (some of them are static) are accesses by many threads at the same time.

Do not block the class! This may lead to very big problems in your code. Instead, use the lock construct to access static resources from your code:

class Abc
{
    private static object _resource;
    static Abc()
    {
        _resource = new object();
    }

    public static void Method1()
    {
        lock (_resource)
        {
            // this will run for only one thread at a time
        }
    }

    public static void Method2()
    {
        lock (_resource)
        {
            // this will run for only one thread at a time
        }
    }
}

Also, you may use the ReadWriteLock ( Slim ) for your synchronization, if one thread need only to read the resource without writing to it.

To lock the entire class, use the following:

lock (typeof(abc))
{
   // code here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM