下面是一个示例代码,演示如何使用ThreadLocal
```csharp
using System;
using System.Threading;
class Program
{
static ThreadLocal
static void Main()
{
userInfo.Value = "https://www.yisu.com/ask/User1";
Thread t1 = new Thread(() =>
{
userInfo.Value = "https://www.yisu.com/ask/User2";
Console.WriteLine($"User info in thread 1: {userInfo.Value}");
});
Thread t2 = new Thread(() =>
{
userInfo.Value = "https://www.yisu.com/ask/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