what is thread-local in c#
if you want to use local data in a thread and initialize it for each thread, you can use ThreadLocal<T> class, this class takes Delegate to a method that initializes the value.
class Program
{
public static ThreadLocal<int> _field = new ThreadLocal<int>(() => { return Thread.CurrentThread.ManagedThreadId; });
static void Main(string[] args)
{
new Thread(() => {
for (int i = 0; i < _field.Value; i++)
{
Console.WriteLine("Thread A {0}",i);
}
}).Start();
new Thread(() =>
{
for (int i = 0; i < _field.Value; i++)
{
Console.WriteLine("Thread B {0}", i);
}
}).Start();
Console.ReadKey();
//Thread.CurrentThread gives the info of currewnt running Thread
}
}
class Program
{
public static ThreadLocal<int> _field = new ThreadLocal<int>(() => { return Thread.CurrentThread.ManagedThreadId; });
static void Main(string[] args)
{
new Thread(() => {
for (int i = 0; i < _field.Value; i++)
{
Console.WriteLine("Thread A {0}",i);
}
}).Start();
new Thread(() =>
{
for (int i = 0; i < _field.Value; i++)
{
Console.WriteLine("Thread B {0}", i);
}
}).Start();
Console.ReadKey();
//Thread.CurrentThread gives the info of currewnt running Thread
}
}
Thread B 0
Thread A 0
Thread B 1
Thread A 1
Thread A 2
Thread B 2
Thread B 3
No comments