Sample Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace WebApplication6
{
public partial class About : System.Web.UI.Page
{
[ThreadStatic]
private static int abc = 6;
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("TheadID:" + Thread.CurrentThread.ManagedThreadId + "; value :" + abc);
}
protected void Button1_Click(object sender, EventArgs e)
{
}
}
}
1. Thead Static only initial once, which means only one thread will have "abc=6", the rest are "abc=0"
2. Field "abc" scope is in thread level, which means each thread will have one "abc", and cannot over write each other.
3.TheadStatic field must define as "static" otherwise it will be overwrite when class initial again.

本文探讨了C#中ThreadStatic特性的使用方式及其背后的原理。解释了如何为每个线程分配独立的变量副本,并强调了其初始化特性及作用域限制。

1219

被折叠的 条评论
为什么被折叠?



