Use thread-local storage : LocalDataStoreSlot « Thread « C# / CSharp Tutorial






using System;
using System.Threading;

class MainClass
{
  public static void SetError() 
  {
    Random r = new Random();
    Thread.SetData(Thread.GetNamedDataSlot("Number"), r.Next(100));
    Thread.SetData(Thread.GetNamedDataSlot("Name") ,Thread.CurrentThread.Name);

    Console.WriteLine("Number = " + Thread.GetData(Thread.GetNamedDataSlot("Number")));
    Console.WriteLine("Name = " + Thread.GetData(Thread.GetNamedDataSlot("Name")));
  }

  public static void Main() 
  {
    Thread.AllocateNamedDataSlot("Number");
    Thread.AllocateNamedDataSlot("Name");

    Thread t2 = new Thread(new ThreadStart(SetError));
    t2.Name = "t2";
    t2.Start();

    Thread t3 = new Thread(new ThreadStart(SetError));
    t3.Name = "t3";
    t3.Start();

    Thread.FreeNamedDataSlot("Number");
    Thread.FreeNamedDataSlot("Name");
  }
}
Number = 81
Name = t2
Number = 81
Name = t3








20.26.LocalDataStoreSlot
20.26.1.Thread-local-storage: Unnamed slots
20.26.2.Thread-local-storage: Named slots
20.26.3.Use LocalDataStoreSlot
20.26.4.Thread-static local-storage
20.26.5.Use thread-local storage