One of the nice things about System.String is that two variables having the same contents will point to the same object once they have been interned. So you have the following:
string s1 = "abcdef";string s2 = "abcdef";object o1 = string.Intern(s1);object o2 = string.Intern(s2);Debug.Assert(o1 == o2);
This can be put to good use when you want to use caching... If the non-cache lookup is expensive, say a database call, you want to ensure that the lookup operation will only happen once in the presence of multiple threads. The lock(cache) keyword is ideal but not very granular. An alternative is the lock the cache key:
public string GetFromCacheOrLookup(string key){ lock (string.Intern(key)) { string result = (string)cache[key];
if (result == null) { result = LookupFromDatabase(key); cache[key] = result; } return result; }}
This method allows multiple threads to perform the expensive lookup as long as the key is different; if not then they wait for the initial lookup to complete before continuing.
Page rendered at Saturday, February 11, 2012 4:41:13 PM (GMT Standard Time, UTC+00:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.