ThreadStatic Modified with Static C#

2019-02-01 03:57发布

I have some code where I use a thread static object in C#.

[ThreadStatic]
private DataContext connection 

I was wondering, in this case, what if any change would I get if I put the static modifier on the thread static context?

[ThreadStatic]
private static DataContext connection 

With the first would there be one copy of the context per instance per thread, with the other only one copy per thread?

3条回答
时光不老,我们不散
2楼-- · 2019-02-01 04:34

In the first case it would probably be ignored, whereas in the second case you are correct, one instance per thread.

查看更多
我只想做你的唯一
3楼-- · 2019-02-01 04:42

The ThreadStaticAttribute is only designed to be used on static variables, as MSDN points out. If you use it on an instance variable, I suspect it will do precisely nothing.

查看更多
在下西门庆
4楼-- · 2019-02-01 04:58

MSDN says :

Indicates that the value of a static field is unique for each thread.

So I guess you first case is incorrect... the attribute will probably be ignored

查看更多
登录 后发表回答