简体   繁体   中英

ThreadStatic Modified with Static C#

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?

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.

在第一种情况下,它可能会被忽略,而在第二种情况下,您是正确的,每个线程一个实例。

In Microsoft Docs, it says :

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

So I guess your first case is incorrect. The attribute will probably be ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM