在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