When I call WrapperAsync
AsyncLocalContext.Value
returns null. When I run the same code block outside the method, in the Main
method, AsyncLocalContext.Value
is not null (which is what I would expect).
The functionality is exactly the same yet the results are different. Is this a bug with the Asynclocal
class or is there another explanation?
internal class Program
{
private static readonly AsyncLocal<string> AsyncLocalContext = new AsyncLocal<string>();
private static void Main()
{
const string text = "surprise!";
WrapperAsync(text).Wait();
Console.WriteLine("Get is null: " + (AsyncLocalContext.Value == null));
// AsyncLocalContext.Value is null
var value = GetValueAsync(text).Result;
AsyncLocalContext.Value = value;
Console.WriteLine("Get is null: " + (AsyncLocalContext.Value == null));
// AsyncLocalContext.Value is not null
Console.Read();
}
private static async Task WrapperAsync(string text)
{
var value = await GetValueAsync(text);
AsyncLocalContext.Value = value;
}
private static async Task<string> GetValueAsync(string text)
{
await Task.Delay(0);
return text;
}
}