ThreadLocal creates a wrapper of Lazy and creates a truly ThreadLocal object. Lets look into code how to build a ThreadLocal object.
public void CreateThreadLocal()
{
ThreadLocal<List<float>> local = new ThreadLocal<List<float>>(() => this.GetNumberList(Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(5000);
List<float> numbers = local.Value;
foreach (float num in numbers)
Console.WriteLine(num);
}
private List<float> GetNumberList(int p)
{
Random rand = new Random(p);
List<float> items = new List<float>();
for(int i = 0; i<10;i++)
items.Add(rand.Next();
return items;
}
Read more: Daily .Net Tips
QR: