【发布时间】:2011-09-16 16:32:29
【问题描述】:
public class MyClass<T>
{
public static readonly String MyStringValue;
static MyClass()
{
MyStringValue = GenerateString();
}
private static String GenerateString()
{
//Dynamically generated ONCE per type (hence, not const)
}
public void Foo()
{
Console.WriteLine(MyStringValue);
}
}
我的理解是,在类上调用静态构造函数之前,不会生成静态只读字符串。但是,在访问静态方法或变量之一之前,不会调用静态构造函数。
在多线程环境中是否可能因此而遇到问题?基本上,默认情况下静态构造函数是单例锁定还是我必须自己这样做?那就是……我是否必须执行以下操作:
private static Object MyLock;
static MyClass()
{
lock(MyLock)
{
if (MyStringValue == null)
MyStringValue = GenerateString();
}
}
【问题讨论】:
标签: c# multithreading static singleton readonly