在C#中,ThreadLocal类是用来在多线程环境下存储线程本地数据的。如果想要存储用户信息,可以使用ThreadLocal
下面是一个示例代码,演示如何使用ThreadLocal
```csharp
using System;
using System.Threading;
class Program
{
static ThreadLocal
static void Main()
{
userInfo.Value = "User1";
Thread t1 = new Thread(() =>
{
userInfo.Value = "User2";
Console.WriteLine($"User info in thread 1: {userInfo.Value}");
});
Thread t2 = new Thread(() =>
{
userInfo.Value = "User3";
Console.WriteLine($"User info in thread 2: {userInfo.Value}");
});
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine($"User info in main thread: {userInfo.Value}");
}
}
```
在上面的示例中,我们定义了一个ThreadLocal
运行上面的代码,你会发现每个线程中的用户信息是独立存储的,互不影响。这就是ThreadLocal