我有點困惑清理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
}
}
}
我寫了一個虛擬主機,並做你[R edoing什麼。我沒有得到警告。警告是否指向這個班級? – Dhawalk 2013-03-26 16:53:36
你可以使用使用(ServiceHost)作爲msdn示例在他們的例子中做的 – ilansch 2013-03-26 20:01:06
@Dhawalk是的。 Visual Studio代碼分析器非常具體。您可能會對編譯器警告感到困惑,並且在這種情況下沒有。 – denver 2013-03-27 04:44:46