c# - Is this Method Thread-Safe? -


can please tell me if following method thread safe. also, please assume call _cache.getorcreate(...) thread-safe. method place in application creates or updates region (dictionary). class containing method singleton, multiple threads access it.

    public ienumerable<string> getreportlookupitems<t>(string cachekey, func<ienumerable<string>> factory)     {         dictionary<string, ienumerable<string>> region = _cache.getorcreate("cache-region:lookupitems", () => new dictionary<string, ienumerable<string>>());          ienumerable<string> items;          if (!region.trygetvalue(cachekey, out items))         {             region[cachekey] = items = factory();         }          return items;     }      

no. it's not thread safe.

you're using dictionary<t,u> here, , changing contents. since dictionary<t,u> not thread-safe, calls trygetvalue , setting dictionary key not thread safe.

if change use thread-safe dictionary (such concurrentdictionary<t,u>), potentially have thread-safe method.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -