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.
publicclass SomeClass
{
privatestaticreadonlyobject theLock = newobject();
private List<string> theList = new List<string>();
privatevoid 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.
publicclass SomeClass
{
private List<string> theList = new List<string>();
privatevoid SomeMethod()
{
Interlocked.Exchange(ref theList, new List<string>);
}
}
Not a huge thing, but still handy to have if you prefer slightly cleaner looking code.
Written By: mycodeshare on July 29, 2009 at 16:39
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.