Why the value of an AsyncLocal
field is not preserved when is set from an asynchronous method of a class. Consider this example:
var scope = new TestScope();
// The default value is 0
Console.WriteLine(scope.Counter.Value);
// Setting the vlaue to 2
await scope.SetValueAsync();
Console.WriteLine(scope.Counter.Value);
class TestScope
{
public readonly AsyncLocal<int> Counter = new AsyncLocal<int> { Value = 0 };
public async Task SetValueAsync()
{
this.Counter.Value = 2;
await Task.Yield();
}
}
The expected output should be:
0
2
But the actual is:
0
0
Why the async context is changed when exiting the SetValueAsync
method?