Home > Enterprise >  C# Solution for thread safe read write updates to static variables with read write synchronization
C# Solution for thread safe read write updates to static variables with read write synchronization

Time:08-31

In my project I'm using some static variables which I use for storing values during the running lifetime of the application. Now, 99% of the time I'm only reading these values but from time to time I also need to update them and this will happen from different threads.

When thinking about what might happen with two different threads trying to access the same propery e.g. concurrent read/write, I started to conclude that some form of synchronization would needed in order to avoid unexpected values being returned between different process or some risk of race conditions.

In essence I needed to derive a single source of truth. I realise that some propeties are atomic like booleans, but my methodoloy mostly applies for the purpose of strings.

One of the challenges is that these static variables are referenced in many places and between different classes, so I also had to figure out an efficient way to solve this challenge without lots of code re-write.

I've decided to use concurrent dictionaries:

public static readonly ConcurrentDictionary<string, string> AppRunTimeStringDictionary = new();
public static readonly ConcurrentDictionary<string, int> AppRunTimeIntegerDictionary = new();
public static readonly ConcurrentDictionary<string, bool> AppRunTimeBooleanDictionary = new();

In my program.cs file, during the earliest stages of startup I simply add all of the properties needed for the running app:

DeviceProvisioning.AppRunTimeBooleanDictionary.TryAdd("UseGpsReceiver", false);
DeviceProvisioning.AppRunTimeStringDictionary.TryAdd("Latitude", String.Empty);
DeviceProvisioning.AppRunTimeStringDictionary.TryAdd("Longitude", String.Empty);

Then in one of my classes I hard code these properties:

public static bool? UseGpsReceiver
{
    get
    {
        if (AppRunTimeBooleanDictionary.TryGetValue("UseGpsReceiver", out var returnedValue))
            return returnedValue;
        return null;
    }
}
public static string? Latitude
{
    get
    {
        if (AppRunTimeStringDictionary.TryGetValue("Latitude", out var returnedValue))
            return returnedValue;
        return null;
    }
}
public static string? Longitude
{
    get
    {
        if (AppRunTimeStringDictionary.TryGetValue("Longitude", out var returnedValue))
            return returnedValue;
        return null;
    }
}

Now for updating these properties, which happens rarely but will be done every now and then, I'm updating these in just one location i.e. using a single method. This way I can use this common method and simply add more prperties to the switch case over time.

public static void SetRunTimeSettings(string property, object value)
{
    switch (property)
    {
        case "UseGpsReceiver":
            // code block
            if (AppRunTimeBooleanDictionary.TryGetValue("UseGpsReceiver", out var useGpsReceiver))
            { AppRunTimeBooleanDictionary.TryUpdate("UseGpsReceiver", (bool)value, useGpsReceiver); }
            break;
        case "Latitude":
            // code block
            if (AppRunTimeStringDictionary.TryGetValue("Latitude", out var latitude))
            { AppRunTimeStringDictionary.TryUpdate("Latitude", (string)value, latitude); }
            break;
        case "Longitude":
            // code block
            if (AppRunTimeStringDictionary.TryGetValue("Latitude", out var longitude))
            { AppRunTimeStringDictionary.TryUpdate("Latitude", (string)value, longitude); }
            break;
    }
}

If I want to update a property then I simply invoke the method as such:

MyClassName.SetRunTimeSettings("UseGpsReceiver", true);
MyClassName.SetRunTimeSettings("Latitude", "51.1234");
MyClassName.SetRunTimeSettings("Longitude", "51.5678");

Becuase the properties themselves are public static then I can use the getter from anywhere in the app.

From my intial testing, everything seems to work.

Perceived advantages in this approach:

  • Using a seperate dictionary for each type of property collection i.e. strings/integers etc, means I can simply add more properties to the dictonary any time in the future without the need for refercing a model class in the dictionary, as opposed to the dictionary below:

    public static readonly ConcurrentDictionary<string, myModelClass> AppRunTimeStringDictionary = new();

  • Use of the concurrent dictionary (my understading) is that any process trying to read the property value from the dictionary will always get the latest value, if a property is being updated then I have less risk in reading an old value. Not such an issue for structured logging but if I was storing keys/secrets/connection strings or anything else, reading an old value might stop some process from being able to function correctly.

  • Using the concurrent dictionary means I dont have to hand craft my own locking mechanisms, which many people seem not to like doing.

  • Dictionary applies its own internal locks on the individual objects, so any property not being updated can still be read by other processes without much delay.

  • If the public static getter ever returned a null value, my thoughts are it would be better to return a null value rather than returning the wrong value. I could always implement some kind of polly or retry mechanism somewhere from the calling process, some short delay before trying to retrieve the property value again (by which time it should have been updated from the other thread that was currently updating it)

Appreciate there will be other ways to approach this, so really what I'm asking here is whether anyone sees any issue in my approach?

I'm not planning to add that many properties to each dictionary, I just want a way to ensure that reads and writes are happening with some form of synchronization and order.

CodePudding user response:

Not everyone would agree with me on this one but my personal approach would be to have a single dictionary of the following type:

Dictionary<string, object>

Wrapped in a separate class with the following methods such as AddValue, GetValue, HasKey, HasValue, and UpdateValue with lock statements. Also notice that you'll have to use somewhat generic methods in order to be able to retrieve the value with the actual type and a default value. For example:

public static T GetValue<T>(string key, T defaultValue)

Also, I don't see a problem with your approach but if you want to synchronize things then you'll need n dedicated locks for n dictionaries which I don't think is a clean way; unless I'm missing something, and of course registering multiple dictionaries in design time can be a headache.

CodePudding user response:

If you are only setting a single string / int / bool at a time, then you don't need to any thread safety. If you are assigning any single value smaller than a machine word, any reading thread will either see the before value or the after value.

However it looks like you intend to set three values at the same time;

MyClassName.SetRunTimeSettings("UseGpsReceiver", true);
MyClassName.SetRunTimeSettings("Latitude", "51.1234");
MyClassName.SetRunTimeSettings("Longitude", "51.5678");

And I assume you want any reader to see either the old values or the new values. In this case you would need some thread synchronisation around every read / write. Which your current code doesn't have.

You could instead store the three values in a class, then update the reference to that instance in one write operation.

public class GpsSettings{
    public bool UseGpsReceiver { get; init; }
    public double Latitude { get; init; }
    public double Longitude { get; init; }
    public static GpsSettings Current;
}
...

// write
GpsSettings.Current = new GpsSettings {
    UseGpsReceiver = true,
    Latitude = 51.1234,
    Longitude = 51.5678
};

// read
var gps = GpsSettings.Current;
var location = $"{gps.Latitude}, {gps.Longitude}";

// but never do this;
var location = $"{GpsSettings.Current.Latitude}, {GpsSettings.Current.Longitude}";

  • Related