2010-10-20 55 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

你並不需要使用應用程序狀態的所有。