ThreadStatic attribute

static field marked with ThreadStaticAttribute is not shared between threads. Each executing thread has a separate instance of the field, and independently sets and gets values for that field. If the field is accessed on a different thread, it will contain a different value.

1. ThreadStatic must on top of a static member

2. DO NOT specify the initial value/reference, it won't take effect.


Here is the reference and test code.


http://msdn.microsoft.com/en-us/library/system.threadstaticattribute.aspx

http://blogs.msdn.com/b/jfoscoding/archive/2006/07/18/670497.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication1
{
    class ThreadStaticTest
    {
        public static void _Main()
        {
            ThreadStaticTest1 test = new ThreadStaticTest1();
            new Thread(new ThreadStart(test.Run)).Start();
            Console.ReadLine();
            new Thread(new ThreadStart(test.Run)).Start();
            Console.ReadLine();
            test.wait.Set();
        }
    }

    class ThreadStaticTest1
    {
        [ThreadStatic]
        private static string strTreadStatic="stat";

        private static string strNonThreadStatic="nonstat";

        public EventWaitHandle wait;

        public ThreadStaticTest1()
        {
            wait = new EventWaitHandle(false, EventResetMode.ManualReset);
        }
        private void Display()
        {
            Console.WriteLine("Static: " + strTreadStatic);
            Console.WriteLine("Non static: " + strNonThreadStatic);
        }

        public void Run()
        {
            Console.WriteLine("Original\r\n===========");
            Display();

            strTreadStatic = Guid.NewGuid().ToString();
            strNonThreadStatic = Guid.NewGuid().ToString();
            Console.WriteLine("Changed\r\n============");
            Display();
            wait.WaitOne();
            Console.WriteLine("quit Run");
        }
    }
}

Original
===========
Static:
Non static: nonstat
Changed
============
Static: 4037bdc9-68e6-4035-b6bb-e9ecc4f9b4e2
Non static: 262a1339-9957-4fe2-9e49-bd0fa9450fcc


Original
===========
Static:
Non static: 262a1339-9957-4fe2-9e49-bd0fa9450fcc
Changed
============
Static: 21c971d8-66df-4eb5-bd7c-a63c50951a3f
Non static: 723b2f9d-9027-41f3-b491-47a027db6102


quit Run
quit Run
Press any key to continue . . .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值