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

时间:2010-03-02 22:23:03

标签: 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...
    }
}

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

IoC本身看起来不错,但如果resolver不是线程安全的话,整个结构将不是线程安全的。如果你想为每个线程设置解析器,你可以使用属性[ThreadStatic]

相关问题