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 #!