ThreadStatic特性简介(转)

在程序中,类的静态成员变量(c#:static;vb:shared),在使用时,会在该类的多个实例之间共享。

在多线程场合下,也不例外。有些读者或许会想到如何创建每个线程自己的静态变量呢,这里ThreadStaticAttribute就提供了一种十分简单的方法。

可以通过追加自定义特性“c#:[ThreadStatic];vb:<ThreadStatic>”的方法来实现。

具体可以参照下面的例子:

 class Program
    {
        static void Main(string[] args)
        {
            
                Thread t1 = new Thread(new ThreadStart(ThreadProc));
                Thread t2 = new Thread(new ThreadStart(ThreadProc));
                t1.Name = "Thread1";
                t2.Name = "THread2";
                t1.Start();
                t2.Start();
            
            Console.WriteLine("Press Enter key to exit...");
            Console.ReadLine();
        }

        [ThreadStatic]
        static int ThreadStaticValue;
        static int StaticValue;

        static Random r = new Random();
        
        public static void ThreadProc()
        {
            StaticValue = ThreadStaticValue = r.Next(1, 10);
            while(true)
            {
                if (Thread.CurrentThread.Name == "Thread1")
                {
                    StaticValue++;
                    ThreadStaticValue++;    
                }
                Console.WriteLine("{0}: ThreadStatic:{1};  Static:{2}", Thread.CurrentThread.Name, ThreadStaticValue, StaticValue);
                Thread.Sleep(500);
            }
        }

    }

可以看到,代码中定义了两个静态变量,一个是被ThreadStatic特性修饰的ThreadStaticValue变量,还有一个就是一般的静态变量。

我们在程序中起了2个线程,用来查看实行的结果。

首先,我们使用随机数初始化了两个静态成员变量,然后线程1每过0.5秒把变量自增长1。

通过值的变化,我们就可以容易理解ThreadStatic的用途了。

 

参考资料:

msdn的说明

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

转自:http://www.cnblogs.com/helloworldexcepition/archive/2012/01/08/2316398.html

posted @ 2014-08-14 09:10  邹邹  Views(1840)  Comments(0)    收藏  举报