Search code examples
c#multithreadingcallcontext

Why AsyncLocal is different from CallContext


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.


Solution

  • You thinking of ThreadLocal? AsyncLocal can flow across threads as it says

    Because the task-based asynchronous programming model tends to abstract the use of threads, AsyncLocal instances can be used to persist data across threads.