一码屏穿

导航

ThreadStatic特性简介

ThreadStaticAttribute

在程序中,类的静态成员变量(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


posted on 2012-01-08 14:25  一码屏穿  阅读(1981)  评论(1编辑  收藏  举报