开发者

are static classes shared among different threads in C#

I need to share a value between threads without exceed开发者_如何学Cing it's boundary. Does a static variable do this?


Static variables are shared across multiple threads within an AppDomain. All threads will see, and act, upon the same instance of a static variable. As such, if you're using static, you will likely want to use some form of synchronization to protect the access of that variable.

If you want to have a thread-local variable, the ThreadLocal<T> class makes this easy. It provides a means of generating and using data that is unique per thread.


You mean you want the variable to be thread-local?

You can either use the [ThreadStatic] attribute or the ThreadLocal<T> class from .NET 4.

Personally I'd prefer ThreadLocal<T> if you are using .NET 4 - but better still would be to avoid this sort of context if you can. Can you encapsulate the information into an instance which is used to start the thread, for example?


You decorate it with the ThreadStaticAttribute, to make the static variable share across only the thread it is initialized in.

Static variables by default are across all threads in an AppDomain.


Yes, apply theThreadStaticAttribute


Yes You need to watch out for synchronization though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜