Reputation: 113
Context
I'm working on a C# project where I want to achieve the following behavior:
C1
to Cn
with specific valid combination for their properties.C1
to Cn
to have a unique instance for every valid property combination.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