When I call WrapperAsync
AsyncLocalContext.Value
returns null. When I run the same code block outside the method, in the Main
method,
Follow this link AsyncLocal Class on MSDN
AsyncLocal
represents ambient data that is local to a given asynchronous control flow, such as an asynchronous method
It means that your code uses different values when it's accesses from another async
method such as WrapperAsync
and your main thread contains another value
[UPDATE]
Not obvious thing to understand, but here is explanation. Control Flow in Async Programs. This is how your thread is changed when you do not expect this.
This is how Control Flow working with async
public class Program
{
private static readonly AsyncLocal AsyncLocalContext = new AsyncLocal();
public static void Main(string[] args)
{
AsyncLocalContext.Value = "No surprise";
WrapperAsync("surprise!");
Console.WriteLine("Main: " + AsyncLocalContext.Value);
}
private static async void WrapperAsync(string text)
{
Console.WriteLine("WrapperAsync before: " + AsyncLocalContext.Value);
AsyncLocalContext.Value = text;
Console.WriteLine("WrapperAsync after: " + AsyncLocalContext.Value);
}
}
Output is:
WrapperAsync before: No surprise
WrapperAsync after: surprise!
Main: No surprise
[/UPDATE]