Keyword for C# equivalent to Java’s "Synchronized"

Asked

Viewed 153 times

3

Problem

I am implementing a connection manager that implements the standard Singleton, managing a pool connections with unique keys for each new connection. So I’m having problems with the parallelism of my manager, because the same can be called by several threads, which causes attempted connection duplicity errors with the same key.

Example:

I would like something in C# similar to this in Java:

synchronized(instances) // ou synchronized no método
{
    if (!instances.ContainsKey(key))
    {
        // ... create connection
        instances.Add(key, /* add connection */);
    }
    return instances.get(key);
}

Question

  • What would be equivalent form synchronized from Java to C#? (can be for method or for code block)
  • How does this form work? How should I use it? What are the differences from synchronized java?

I would like a brief explanation of the equivalent solution in C#!

2 answers

4


In C# the lock for code blocks only. Essentially just swap the keyword. There is semantic equivalence.

lock (instances) {
    if (!instances.ContainsKey(key)) {
        // ... create connection
        instances.Add(key, /* add connection */);
    }
    return instances[key];

In this example it may be more interesting to use a TryAdd(). Or maybe use a concurrent dictionary, as the example on the documentation page shows linked of that method.

In C# it is only syntactic sugar, so this code:

lock (lockObject) {
    DoSomething();
}

turns into this:

object obj = (System.Object)lockObject;
System.Threading.Monitor.Enter(obj);
try {
    DoSomething();
} finally {
    System.Threading.Monitor.Exit(obj);
}

I put in the Github for future reference.

For methods you need to use an attribute: MethodImpl(MethodImplOptions.Synchronized).

There’s a Singleton’s concurrent implementation in the Microsoft documentation.

Jon Skeet wrote about it too.

Question on the subject.

  • Thanks for the reply bigown! Just to understand, if in case I use ConcurrentDictionary and use the method TryAdd() to add the elements in the ConcurrentDictionary, would be redundant and unnecessary (for my case) the use of lock to avoid parallelism of access to the code block, as I understood the TryAdd() already does this job. Correct?

  • I believe so. Of course I didn’t see the whole context, I don’t know if it’s the best approach.

  • Okay, thanks again. I really think ConcurrentDictionar‌​y apparently works as I mentioned in the previous comment, as it is possible to understand in the description comment of class: "Represents a thread-safe Collection of key/value pairs that can be accessed by Multiple threads concurrently.", which would be freely translated: "Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads simultaneously."

  • Yes, I understand too.

2

Fernando, from what I could understand about the "Synchronized" it protects the code so that only one thread can access it at a time, in C# the equivalent is the "lock". ex.:

static object _locker = new object();
...
public static void MeuMetodo()
{
  lock(_locker)
  {
    //meu código
  }
}

I hope I’ve helped.

  • Thank you for the reply Éderson! Your answer is correct and works perfectly for my case (at least in my tests, hehe), I only marked as a response to the bigown because I ended up using one of the alternatives (ConcurrentDictionary TryAdd()) that he cited in his reply that for my case seemed to be more suitable (as far as I tested also). (It is already accounted for my +1 =D).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.