Please, consider the following example code:
using System.Diagnostics;
using System.Threading.Tasks;
public struct AStruct
{
public int Value;
public async Task SetValueAsync()
{
Value = await Task.Run(() => 1);
}
public void SetValue()
{
Value = 1;
}
}
class Program
{
static void Main(string[] args)
{
Test(new AStruct());
TestAsync(new AStruct()).Wait();
}
private static async Task TestAsync(AStruct x)
{
Debug.Assert(x.Value == 0);
await x.SetValueAsync();
Debug.Assert(x.Value == 0);
}
private static void Test(AStruct x)
{
Debug.Assert(x.Value == 0);
x.SetValue();
Debug.Assert(x.Value == 1);
}
}
Notice the difference between Test
and TestAsync
. This code satisfies all the assertions.
I guess looking at the code with Reflector will tell me why, but still this is something I did not expect at all.
Of course, changing AStruct
to be a class instead of a struct does fail the second assertion in TestAsync
- as I would expect it in the first place.
My question is this - besides not using mutable structs with async/await is there an elegant way to make them coexist peacefully?