I have a class with two properties and two methods. Like the one below for example. (please ignore the data types or return types, it’s just a typical scenario)
// The methods could be invoked by multiple threads
public class Stock
{
private static int FaceValue {get; set;}
private static int Percent (get; set;}
// method that updates the two properties
Public void UpdateStock()
{
FaceValue += 1;
Percent = FaceValue * 100;
}
// method that reads the two properties
public int[] GetStockQuote()
{
return new int[] { FaceValue, Percent};
}
}
I need to ensure this class is thread safe. I could use lock(obj) in both the methods as one technique to make it threadsafe but what would be the best technique to make it thread safe, considering the following:
-
There are only two properties that is read/updated. So, not sure if locking inside the methods is a good technique.
-
Will it be enough if I just make the properties thread safe rather than the methods or the class ?
-
Also, is there a way to make the whole class thread safe rather than individual methods or properties ? Any recommended lock techniques from .Net 4.0 ?
Just wondering if I am thinking through this right or may be I am over complicating it considering these. Many thanks in advance to help me get this clear.
Mani
In general, a
lockis probably the simplest approach here.A potentially better alternative would be to make this class immutable. If you make it so you can’t change the values within the class once it’s created, you no longer have to worry when reading the values, as there’s no way for them to be modified.
In this case, that could be done by having a constructor that takes the two values, and changing
UpdateStockto be more like:Edit:
Now that you’ve made FaceValue and Percent static, you will need synchronization. A
lockis likely the simplest option here.With a single value, you could potentially use the Interlocked class to handle updates atomically, but there is no way to do an atomic update of both values*, which is likely required for the thread safety to be done properly. In this case, synchronizing via a
lockwill solve your issue.*Note: This could possibly be done without a lock via
Interlocked.CompareExchangeif you put both values within a class, and exchanged the entire class instance – but that’s likely a lot more trouble than it’s worth.