是静态类在C#中不同的线程之间共享

问题描述:

我需要线程之间共享的值不超过它的边界。难道一个静态变量做到这一点?

I need to share a value between threads without exceeding it's boundary. Does a static variable do this?

您的意思是你想要的变量是线程本地?

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

您既可以使用 [ThreadStatic] 属性或的 的ThreadLocal< T> 从.NET 4类

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

我个人更喜欢的ThreadLocal&LT; T&GT; 如果你的的使用.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?