I just came across a strange behavior with using async methods in structures. Can somebody explain why this is happening and most importantly if there is a workaround? Here is a simple test structure just for the sake of a demonstration of the problem
public struct Structure
{
private int _Value;
public Structure(int iValue)
{
_Value = iValue;
}
public void Change(int iValue)
{
_Value = iValue;
}
public async Task ChangeAsync(int iValue)
{
await Task.Delay(1);
_Value = iValue;
}
}
Now, let's use the structure and do the following calls
var sInstance = new Structure(25);
sInstance.Change(35);
await sInstance.ChangeAsync(45);
The first line instantiates the structure and the sInstance._Value
value is 25
. The second line updates the sInstance._Value
value and it becomes 35
. Now the third line does not do anything but I would expect it to update the sInstance._Value
value to 45
however the sInstance._Value
stays 35
. Why? Is there a way to write an async method for a structure and change a structure field's value?