是的,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實例。當我們在不同的線程中修改這些實例的值時,它們不會相互影響。