是否有可能在静态 ctor 完成 运行(在多线程环境中)之前创建 class(常规 ctor)的实例?
Is there any chance a instance of a class (regular ctor) will be created before the static ctor completes it's run (in a multi-threaded environment)?
我有一个静态构造函数,它从我的配置服务器获取配置并设置一个静态变量。
我有一个常规构造函数,它根据该配置实例化一些属性。
这是我的例子 class:
public class MyClass
{
private static MyConfig _config;
private UnitOfWork _uow;
static MyClass(){
// This takes some time since it's a web service call!!!
_config = ConfigService.GetConfig();
}
public MyClass(){
_uow = CreateUow(_config.UOWConnectionString);
}
public Response DoSomething(){
// logic with _uow
}
}
假设我有一个接收多个请求的 WCF 服务,每个请求实例化 MyClass
和 运行 的 DoSomething
方法。
静态 ctor 执行 Web 服务调用,需要一些时间才能获得结果。
我可以确定静态 ctor 会在 任何请求 收到 MyClass
实例之前完成 运行ning 吗?
我知道静态 ctors 是线程安全的。
在静态 ctor 完成 运行 之前,创建新实例是否有任何锁定?
在创建任何实例之前保证静态构造函数是运行。来自 MSDN.
A static constructor is called automatically to initialize the class
before the first instance is created or any static members are
referenced.
我有一个静态构造函数,它从我的配置服务器获取配置并设置一个静态变量。
我有一个常规构造函数,它根据该配置实例化一些属性。
这是我的例子 class:
public class MyClass
{
private static MyConfig _config;
private UnitOfWork _uow;
static MyClass(){
// This takes some time since it's a web service call!!!
_config = ConfigService.GetConfig();
}
public MyClass(){
_uow = CreateUow(_config.UOWConnectionString);
}
public Response DoSomething(){
// logic with _uow
}
}
假设我有一个接收多个请求的 WCF 服务,每个请求实例化 MyClass
和 运行 的 DoSomething
方法。
静态 ctor 执行 Web 服务调用,需要一些时间才能获得结果。
我可以确定静态 ctor 会在 任何请求 收到 MyClass
实例之前完成 运行ning 吗?
我知道静态 ctors 是线程安全的。
在静态 ctor 完成 运行 之前,创建新实例是否有任何锁定?
在创建任何实例之前保证静态构造函数是运行。来自 MSDN.
A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.