I was reading about Records
in C# and read that they are immutable. And thread safety is written as a benefit of immutability. How immutability provides thread safety. I tried a code sample claiming to provide predictable results by using Records
because they are immutable rather than using shared mutable object. I tried the code and the results were unpredictable:
public record SharedData(int Value);
public static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
ImmutableRecords();
//MutableSharedVariable();
}
static void ImmutableRecords()
{
SharedData sharedData = new SharedData(0);
Task.Run(() =>
{
for (int i = 0; i < 1000; i++)
{
sharedData = sharedData with { Value = sharedData.Value + 1 };
}
});
Task.Run(() =>
{
for (int i = 0; i < 1000; i++)
{
sharedData = sharedData with { Value = sharedData.Value - 1 };
}
});
Task.WaitAll();
Console.WriteLine(sharedData.Value);
}
When I tried to comprehend this code, I see that although sharedData is immutable but it can be replaced with a new instance and that is same as mutable object behavior in the context of multiple threads accessing and writing it. And so the results are unpredictable.
Then why thread safety is listed as an advantage of immutability?