are static classes shared among different threads in C#

前端 未结 5 1623
野性不改
野性不改 2021-02-14 11:44

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

5条回答
  •  执念已碎
    2021-02-14 12:28

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

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

    Personally I'd prefer ThreadLocal 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?

提交回复
热议问题