WebService 是否要呼叫 Dispose ?

  • 3845
  • 0
  • C#
  • 2015-02-25

摘要:WebService 是否要呼叫 Dispose ?

在 StackOverflow 有許多討論到 WebService 是否需要 Dispose 的文章 , 

 

可以參考這些討論串 :

Do I need to dispose a web service reference in ASP.NET?

Dispose a Web Service Proxy class?

IDisposable for WebServices 

 

不過比起這些文章 , 我們來看看 MSDN 怎麼說吧  ,  如下連結 , 

 

WebService.Dispose 方法 , 在一開始就明白敘述如下 , 

 

釋放 MarshalByValueComponent 所使用的資源

 

上文的 MarshalByValueComponent  其實是 WebService 的母類別 , 

 

因此在 WebService 呼叫的 Dispose 方法 , 其實是去呼叫 MarshalByValueComponent  

 

的 Dispose ,  我們開始來看看 MarshalByValueComponent  這個類別的 Dispose 做了甚麼 ,

 

我們可以看到它不但釋放自己本身 hold 住的資源 , 也呼叫了 GC 的部分

 


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

protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				Monitor.Enter(this);
				try
				{
					if (this.site != null && this.site.Container != null)
					{
						this.site.Container.Remove(this);
					}
					if (this.events != null)
					{
						EventHandler eventHandler = (EventHandler)this.events[MarshalByValueComponent.EventDisposed];
						if (eventHandler != null)
						{
							eventHandler(this, EventArgs.Empty);
						}
					}
				}
				finally
				{
					Monitor.Exit(this);
				}
			}
		}

 

 

看來還是要呼叫 Dispose 是比較好的 , 不過在 StackOverflow 文章滿多人

 

提到應該 wrapper Webservice 類別以隔離直接使用或使用 DI framework 的確是很有意義的觀點