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