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#!
Thanks for the reply bigown! Just to understand, if in case I use
ConcurrentDictionary
and use the methodTryAdd()
to add the elements in theConcurrentDictionary
, would be redundant and unnecessary (for my case) the use oflock
to avoid parallelism of access to the code block, as I understood theTryAdd()
already does this job. Correct?– Fernando Leal
I believe so. Of course I didn’t see the whole context, I don’t know if it’s the best approach.
– Maniero
Okay, thanks again. I really think
ConcurrentDictionary
apparently works as I mentioned in the previous comment, as it is possible to understand in the description comment ofclass
: "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."– Fernando Leal
Yes, I understand too.
– Maniero