Thread Static

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值