是的,C#的ThreadLocal
下面是一个使用ThreadLocal
using System;
using System.Threading;
class ComplexObject
{
public int Value { get; set; }
public ComplexObject(int value)
{
Value = value;
}
}
class Program
{
static readonly ThreadLocal<ComplexObject> _threadLocal = new ThreadLocal<ComplexObject>(() => new ComplexObject(0));
static void Main(string[] args)
{
Thread thread1 = new Thread(() =>
{
_threadLocal.Value.Value = 1;
Console.WriteLine($"Thread 1: {_threadLocal.Value.Value}");
});
Thread thread2 = new Thread(() =>
{
_threadLocal.Value.Value = 2;
Console.WriteLine($"Thread 2: {_threadLocal.Value.Value}");
});
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
}
在这个例子中,我们为每个线程创建了一个独立的ComplexObject实例。当我们在不同的线程中修改这些实例的值时,它们不会相互影响。