Keyword for C # equivalent to "synchronized" Java

3

Problem

I'm implementing a connection manager that implements the standard Singleton , managing a pool of single-key connections for each new connection. So I'm trying to get problems with the parallelism of my manager, because it can be called by several threads, which causes duplicate attempts to connect to 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 to synchronized from Java to C #? (can be for method or for block of code)
  • How does this form work? How should I use it? What are the differences compared to synchronized of Java?
  

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

    
asked by anonymous 17.08.2016 / 13:53

2 answers

4

In C # lock is used only for code blocks. Essentially it's just the keyword change. 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 competing dictionary, as shown in the example on the linked documentation page of this method.

In C # it's just syntactic sugar, so this code:

lock (lockObject) {
    DoSomething();
}

becomes this:

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

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

There is a Singleton concurrent deployment in Microsoft documentation .

Jon Skeet wrote about it too .

Question about the subject .

    
17.08.2016 / 14:01
2

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

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

I hope I have helped.

    
17.08.2016 / 14:00