1

Could someone please explain the result of the following sample code. The question is why the resolved thread id in the ThreadContext does not match with the current managed thread id? Is the result from the InjectionFactory cached and shared between all managed threads even if I used PerThreadLifetimeManager in order to cache the delegate result locally for each thread.

       public class ThreadContext
    {
        public ThreadContext(int id)
        {
            ThreadId = id;
        }

        public int ThreadId { get; set; }
    }

    static void Main(string[] args)
    {
        UnityContainer container = new UnityContainer();

        for (int i = 0; i < 5; i++)
        {
            Task.Factory.StartNew(() => DoWork(container));
        }

        Console.ReadLine();
    }

    private static void DoWork(IUnityContainer container)
    {
        int id = System.Threading.Thread.CurrentThread.ManagedThreadId;

        container.RegisterType<ThreadContext>(new PerThreadLifetimeManager(), new InjectionFactory(_ => new ThreadContext(id)));

        Console.WriteLine(id + " -- The current thread id is  = " + container.Resolve<ThreadContext>().ThreadId);
    }
}

Thanks in advance /arash

Steven
  • 166,672
  • 24
  • 332
  • 435

0 Answers0