本文介绍了我需要建立在C#.NET线程安全的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
确定,它不是这个问题有点复杂。
ok, its a little more complicated than the question.
class A
{
static int needsToBeThreadSafe = 0;
public static void M1()
{
needsToBeThreadSafe = RandomNumber();
}
public static void M2()
{
print(needsToBeThreadSafe);
}
}
现在我要求,M1()和M2(间)所称的needsToBeThreadSafe'住宿线程安全的。
now i require that between M1() and M2() calls 'needsToBeThreadSafe' stays Thread Safe.
推荐答案
你也许会想询问的是[ ThreadStatic ]属性。如果你想使用该类的每个线程的 A
以拥有自己独立的价值 needsToBeThreadSafe
,然后你只需要装饰那场与[ ThreadStatic ]属性。
What you might be trying to ask about is the [ThreadStatic] attribute. If you want each thread that uses the class A
to have its own separate value of needsToBeThreadSafe
then you just need to decorate that field with the [ThreadStatic] attribute.
有关更多信息请参考文档 ThreadStaticAttribute
。
For more info refer to the MSDN documentation for ThreadStaticAttribute
.
这篇关于我需要建立在C#.NET线程安全的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!