Links

 

Using Interlocked.Exchange to make a Thread Safe Variable Replacement

When trying to replace static variables in a class, I always used a static object for doing a lock() before the update.
public class SomeClass { private static readonly object theLock = new object(); private List<string> theList = new List<string>(); private void SomeMethod() { lock(theList) { theList = new List<string>(); // this is supposed to be a replacement with a different list } } }
A slightly more elegant way can be used with the System.Threading.Interlocked.Exchange method.
public class SomeClass { private List<string> theList = new List<string>(); private void SomeMethod() { Interlocked.Exchange(ref theList, new List<string>); } }
Not a huge thing, but still handy to have if you prefer slightly cleaner looking code.
Submit a comment, suggestion, or additional information about this snippet
If you login or register, you'll be able to post a comment or provide feedback about this snippet.
Contact Us | Terms of Use