R. Javid
R. Javid

Reputation: 113

C#: How to ensure thread-safe, single-instance objects for valid property combinations?

Context

I'm working on a C# project where I want to achieve the following behavior:

  1. I have classes C1 to Cn with specific valid combination for their properties.
  2. The valid property combinations are stored in a database
  3. I want each class C1 to Cn to have a unique instance for every valid property combination.
  4. All valid instances should be loaded from a single database access.
  5. I want to store all instances centrally, not as static arrays within each class.

The database structure looks like this:

Table C1
P1 P2 P3 P4
---------------
1  1  1  1
2  1  1  1
3  1  1  3
...

Implementation

Here's the pseudocode of my implementation:

public static class Info
{
    private static List<C1> ValidC1s = new();
    ...
    private static List<Cn> ValidCns = new();
    private static bool initialized = false;

    static Info()
    {
        foreach (Ci valid property combination)
              ValidCis.Add(Ci.Get(validProperties));
        initialized = true;
    }
    // for each Ci
    public static Ci? GetCi(Properties properties)
    {
        return ValidCis.SingleOrDefault(x => x.Properties == properties);
    }
}

public class Ci
{
    private Ci(Properties properties)
    {
        this.Properties = properties;
    }

    public static Ci Get(Properties properties)
    {
        if (Info.Initialized)
        {
            Ci ci = Info.GetCi(properties);
            if (ci==null) throw Exception;
            return ci
        }
        else
        {
            return new Ci(properties);
        }
    }

    public Properties Properties { get; }
}

My Concerns: I assume that calling Info.Initialized in the Cis' Get function makes sure the instances are created only from the Info class. However, ChatGPT raised concerns about thread safety if another thread accesses Get before initialization completes. I don't know how to test such a scenario, so my question is:

Questions Is my approach thread-safe and correct? If not, what would be the best way to implement this behavior?

Upvotes: 0

Views: 48

Answers (0)

Related Questions