Running the bellow code you can see that there is a different between CallContext and AsyncLocal.
using System;
using System.Runtime.Remoting.Messaging;
using System.Threading;
namespace AsyncLocalIsDifferentThanCallContext
{
class Program
{
public static AsyncLocal<int> AsyncLocal = new AsyncLocal<int>();
public static int CallContextValue
{
get
{
var data = CallContext.GetData("CallContextValue");
if (data == null)
return 0;
return (int) data;
}
set { CallContext.SetData("CallContextValue", value); }
}
static void Main(string[] args)
{
AsyncLocal.Value = 1;
CallContextValue = 1;
new Thread(() =>
{
Console.WriteLine("From thread AsyncLocal: " + AsyncLocal.Value); // Should be 0 but is 1
Console.WriteLine("From thread CallContext: " + CallContextValue); // Value is 0, as it should be
}).Start();
Console.WriteLine("Main AsyncLocal: " + AsyncLocal.Value);
Console.WriteLine("Main CallContext: " + CallContextValue);
}
}
}
Can you explain why?
I expected the value of AsyncLocal to be unique per thread as the documentation says it should behave and as CallContext behaves.
You thinking of
ThreadLocal?AsyncLocalcan flow across threads as it says