2010-10-20 58 views
0

我有一些代码,我一直在尝试检查线程安全性。我正在使用发现的基本懒惰单体模型here。我想知道如果它将实例放入HttpApplicationState对象,它是否仍然是线程安全的。我需要跨Web应用程序的所有实例访问此实例,因此,如果这不是线程安全的,我如何才能使其线程安全?ApplicationState中C#单例实例的线程安全性


public sealed class EmailWorker { 
    private HttpApplicationState _app; 
    private const EMAIL_WORKER = "EmailWorker"; 

    EmailWorker() { } 

    class NestedWorker { 
     static NestedWorker() { } 
     internal static readonly EmailWorker Instance = new EmailWorker(); 
    } 

    public static void Initialize(HttpApplicationState appState) { 
     _appState = appState; 
     _appState.Lock(); 
     if (_appState[EMAIL_WORKER] == null) { 
      _appState.Add(EMAIL_WORKER, NestedWorker.Instance); 
     } 
     _appState.UnLock(); 
    } 

    public static EmailWorker Instance { 
     get { 
      // TODO: If we haven't called Initialize() first then throw exception 
      return (EmailWorker)_appState[EMAIL_WORKER]; 
     } 
    } 
} 

回答

0

它应该是线程安全的,但为什么要麻烦?

“标准”单身也将是整个应用程序访问,而且不需要注射并保持到HttpApplicationState参考:

public sealed class EmailWorker 
{ 
    private EmailWorker() { } 

    private static class NestedWorker 
    { 
     static NestedWorker() { } 

     internal static readonly EmailWorker Instance = new EmailWorker(); 
    } 

    public static EmailWorker Instance 
    { 
     get { return NestedWorker.Instance; } 
    } 
} 
+0

稍作澄清。我需要通过Web应用程序的所有实例访问它。 EmailWorker类是在ApplicationStart事件上启动的线程。 – robbymurphy 2010-10-20 22:49:29

+1

@robby:但是'HttpApplicationState'只是每个应用程序,与“标准”单例完全一样。 – LukeH 2010-10-20 22:53:18

+0

是因为这个实例是静态的吗? – robbymurphy 2010-10-20 23:08:14

1

你并不需要使用应用程序状态的所有。