2013-03-26 109 views
3

我有點困惑清理ServiceHost的最佳方法。由於Visual Studio代碼分析器的CA1001警告提示我爲我的類實現了IDisposable接口,我意識到了代碼中的問題。正確清理System.ServiceModel.ServiceHost

我已閱讀關於IDisposable的討論,並熟悉典型用例,但發現自己在這種情況下感到困惑。確保ServiceHost被處置並可能滿足CA1001的正確方法是什麼?謝謝。

我的代碼看起來像下面這樣:

public class MyClass 
{ 
    private ServiceHost host = null; 

    public void StartListening(...) 
    { 
     // make sure we are not already listening for connections 
     if (host != null && host.State != CommunicationState.Closed) 
      StopListening(); 

     // create service host instance 
     host = new ServiceHostWithData(typeof(ServiceHandler), address); 

     // do a bunch of configuration stuff on the host 

     host.Open(); 
    } 

    public void StopListening() 
    { 
     // if we are not closed 
     if ((host != null) && (host.State != CommunicationState.Closed)) 
     { 
      host.Close(); 
      host = null; 
     } 
     else // we are null or closed 
     { 
      host = null; // if it isn't null, and it is already closed, then we set it to null 
     } 
    } 
} 

+0

我寫了一個虛擬主機,並做你[R edoing什麼。我沒有得到警告。警告是否指向這個班級? – Dhawalk 2013-03-26 16:53:36

+1

你可以使用使用(ServiceHost)作爲msdn示例在他們的例子中做的 – ilansch 2013-03-26 20:01:06

+0

@Dhawalk是的。 Visual Studio代碼分析器非常具體。您可能會對編譯器警告感到困惑,並且在這種情況下沒有。 – denver 2013-03-27 04:44:46

回答

5

你的類應該實現IDisposable。基於從MSDN頁面的例子:

public class MyClass : IDisposable 
{ 
    private bool disposed = false; 
    private ServiceHost host = null; 

    public void StartListening(...) 
    { 
     // .... 
    } 

    public void StopListening() 
    { 
     // ... 
    } 

    public void Dispose() 
    { 
     Dispose(true); 
     GC.SuppressFinalize(this); 
    } 

    protected virtual void Dispose(bool disposing) 
    { 
     if(!this.disposed) 
     { 
      if(disposing) 
      { 
       this.StopListening(); 
      } 

      disposed = true; 
     } 
    } 

    ~MyClass() 
    { 
     Dispose(false); 
    } 
} 
+0

謝謝。根據ServerHost調用ServerHost.Close相當於在MyClass Dispose函數中調用ServerHost.Dispose? – denver 2013-03-27 04:42:44

+2

Close和Dispose基本相同(請參閱此處的答案:http://stackoverflow.com/questions/4964161/wcf-how-to-stop-myservicehost-close-from-disposing-of-myservicehost-object),所以你也可以使用。請注意,在ServiceHost上關閉/處理可能會拋出一個異常(!),因此您可能想要嘗試/捕獲該塊,特別是如果您正在執行MyClass Dispose函數中的其他工作。 – TheNextman 2013-03-27 12:30:04

+0

感謝您的幫助 – denver 2013-03-27 14:01:39