使用静态 C# 修改的 ThreadStatic
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/868537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ThreadStatic Modified with Static C#
提问by Anthony D
I have some code where I use a thread static object in C#.
我有一些代码在 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?
我想知道,在这种情况下,如果我将 static 修饰符放在线程静态上下文中,我会得到什么改变吗?
[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?
对于第一个,每个线程每个实例有一个上下文副本,另一个每个线程只有一个副本吗?
采纳答案by Noldorin
The ThreadStaticAttribute
is only designed to be used on static variables, as the documentation points out. If you use it on an instance variable, I suspect it will do precisely nothing.
在ThreadStaticAttribute
被设计为只对静态变量使用,如文档指出。如果你在一个实例变量上使用它,我怀疑它什么都不做。
回答by Otávio Décio
In the first case it would probably be ignored, whereas in the second case you are correct, one instance per thread.
在第一种情况下,它可能会被忽略,而在第二种情况下,您是正确的,每个线程一个实例。
回答by Thomas Levesque
MSDN says :
MSDN 说:
Indicates that the value of a staticfield is unique for each thread.
表示静态字段的值对于每个线程都是唯一的。
So I guess you first case is incorrect... the attribute will probably be ignored
所以我猜你的第一种情况是不正确的......该属性可能会被忽略