是静态类在C#中不同的线程之间共享 [英] are static classes shared among different threads in C#

查看:122
本文介绍了是静态类在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< T> 如果你的的使用.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?

这篇关于是静态类在C#中不同的线程之间共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆