是的,C#的ThreadLocal类可以用于复杂对象。ThreadLocal为每个线程存储一个独立的T类型的值副本,因此你可以在不同的线程中使用不同的复杂对象实例。需要注意的是,ThreadLocal实例本身不是线程安全的,你需要确保在使用过程中遵循正确的同步策略。
下面是一个使用ThreadLocal的例子,其中T是一个复杂对象:
using System;
using System.Threading;
class ComplexObject
{
public int Value { get; set; }
public ComplexObject(int value)
{
Value = value;
}
}
class Program
{
static readonly ThreadLocal _threadLocal = new ThreadLocal(() => 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实例。当我们在不同的线程中修改这些实例的值时,它们不会相互影响。