ThreadStatic attribute
来源:互联网 发布:看日漫原版的软件 编辑:程序博客网 时间:2024/05/04 11:56
A 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 . . .
- ThreadStatic attribute
- ThreadStatic
- ThreadStatic属性用法
- ThreadStatic属性用法
- Attribute
- Attribute
- attribute
- attribute
- attribute
- attribute
- attribute
- attribute
- Attribute
- Attribute
- Attribute
- Attribute
- 线程静态字段(ThreadStatic) 延迟初始化
- ThreadStatic静态字段在每个线程里的唯一性
- RS-232/RS-485协议转换器
- MySQL之alter语句用法总结
- jni如何通过回调传对象
- Map接口及其重要实现类的用法
- SIFT算法以及RANSAC算法中的数据归一化研究
- ThreadStatic attribute
- APIO10-特别行动队-题解
- 中南大学刘嘉忆(刘路)论文--破解西塔潘猜想.pdf
- el端子
- 用V$BH查看表查看数据缓冲区
- 分享20个超酷的酒店类网站设计
- 数字时代的隐私问题, 你是数据的主人吗?
- WINCE6.0系统调用
- zend studio 开发php项目的简单例子