I am probably making a mistake in code below, but where?
MCVE:
class Program
{
struct Test
{
public readonly string A;
public readonly string B;
public Test(string test) => A = B = test;
}
static void Main(string[] args)
{
var test = new Test();
int counter = 0;
Task.Run(() =>
{
while (true)
{
counter++;
test = new Test(counter.ToString());
}
});
Task.Run(() =>
{
Thread.Sleep(100);
while (true)
{
var copy = test; // create a copy of test
if (copy.A != copy.B)
Console.WriteLine($"{copy.A} {copy.B}"); // occurs often, why?
}
});
Console.ReadKey();
}
}
Output on my PC:
808317 808318
812792 812793
814938 814939
815423 815428
815779 815780
816280 816281
816915 816916
Why?
It looks like creating copy is a problem. Right? Of course I can use lock
to access test
, but that means that only immutable struct with single member can be thread-safe.