类的静态字段在类的实例中是共享的。多个线程修改实例字段的值在对其它线程来说是可见的,这也是clr默认的行为。对静态字段添加ThreadStaticAttribute标记可以改变这种默认的行为。
ThreadStaticAttribute
指示静态字段的值对于每个线程都是唯一的。用 ThreadStaticAttribute 标记的 static 字段不在线程之间共享。每个执行线程都有单独的字段实例,并且独立地设置及获取该字段的值。如果在不同的线程中访问该字段,则该字段将包含不同的值。
示例代码
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace NetThreading
{
/// <summary>
/// 测试一般静态字段与有ThreadStatic 标记的静态字段在
/// 多线程执行中的区别
/// </summary>
public class TheadStaticAttributeApp:IMain
{
#region IMain 成员
public void MainRun()
{
MyStaticFiledClass myStaticTest = new MyStaticFiledClass();
ThreadStart ts1 = new ThreadStart(myStaticTest.AddXY);
Thread t1 = new Thread(ts1);
Thread t2 = new Thread(ts1);
t1.Start();
t2.Start();
}
#endregion
}
/// <summary>
/// MyStaticTest
/// </summary>
class MyStaticFiledClass
{
/// <summary>
/// 一般静态变量
/// </summary>
static int X=0;
/// <summary>
/// 有ThreadStatic标记的静态变量
/// </summary>
[ThreadStatic]
static int threadStaticX=0;
/// <summary>
/// 分别对x,y 自增
/// </summary>
public void AddXY()
{
for (int i = 0; i < 10; i++)
{
X++;
threadStaticX++;
Thread current = Thread.CurrentThread;
string info = string.Format("threadID:{0} x={1}; [ThreadStatic]threadStaticX={2}", current.ManagedThreadId, X, threadStaticX);
Console.WriteLine(info);
Thread.Sleep(500);
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace NetThreading
{
/// <summary>
/// 测试一般静态字段与有ThreadStatic 标记的静态字段在
/// 多线程执行中的区别
/// </summary>
public class TheadStaticAttributeApp:IMain
{
#region IMain 成员
public void MainRun()
{
MyStaticFiledClass myStaticTest = new MyStaticFiledClass();
ThreadStart ts1 = new ThreadStart(myStaticTest.AddXY);
Thread t1 = new Thread(ts1);
Thread t2 = new Thread(ts1);
t1.Start();
t2.Start();
}
#endregion
}
/// <summary>
/// MyStaticTest
/// </summary>
class MyStaticFiledClass
{
/// <summary>
/// 一般静态变量
/// </summary>
static int X=0;
/// <summary>
/// 有ThreadStatic标记的静态变量
/// </summary>
[ThreadStatic]
static int threadStaticX=0;
/// <summary>
/// 分别对x,y 自增
/// </summary>
public void AddXY()
{
for (int i = 0; i < 10; i++)
{
X++;
threadStaticX++;
Thread current = Thread.CurrentThread;
string info = string.Format("threadID:{0} x={1}; [ThreadStatic]threadStaticX={2}", current.ManagedThreadId, X, threadStaticX);
Console.WriteLine(info);
Thread.Sleep(500);
}
}
}
}
运行结果
分析
具有ThreadStatic标记的静态变量,在每个线程中都有自己的副本。
一般静态变量测试在进程之间共享的。t1线程中对X的修改与t2线程
对X的修改会累积,所以x的值会是20。而对于threadStaticX来说t1
与t2都是各自拥有的threadStaticX副本,所以threadStaticX的值为
10.