C#ASP.NET线程安全静态只读字段

Emi*_*ian 8 asp.net thread-safety

我的ASP.NET项目中有以下代码

public sealed class IoC
{
    private static readonly IDependencyResolver resolver =
        Service.Get("IDependencyResolver") as IDependencyResolver;

    static IoC()
    {
    }

    private IoC()
    {
    }

    public static IDependencyResolver Container
    {
         get
         {
             return resolver;
         }
    }
}

public static class Service
{
    public static object Get(string serviceName)
    {
        // Code to create and return instance...
    }
}
Run Code Online (Sandbox Code Playgroud)

IoC.Container是否是线程安全的?

Tim*_*son 1

静态字段的初始化是线程安全的:也就是说,.NET 运行时保证您的字段只会在程序中初始化一次,无论有多少线程访问它以及以什么顺序。

正如 Andrey 指出的那样,Service.Get方法本身需要是线程安全的。