2013-05-28 38 views
5

我提供了一個HTTP Web服務,我的一個用戶正在Windows 2003計算機上使用C#WebClient類從我的網站檢索數據。我的用戶說WebClient正在創建許多瀏覽器實例,需要關閉。如何在創建後關閉瀏覽器?如何在創建C#WebClient類後關閉瀏覽器?

他的代碼:

Byte[] requestedHTML; 
WebClient client = new WebClient(); 
requestedHTML = client.DownloadData("http://abcabc.com/abc"); 
UTF8Encoding objUTF8 = new UTF8Encoding(); 
string returnMessage = objUTF8.GetString(requestedHTML); 

附:如果這聽起來像是業餘愛好者,我很抱歉,我對C#很陌生。

+2

請不要道歉。我們都在這裏學習。 –

回答

6

WebClient不使用瀏覽器 - 它只是一個基礎協議的包裝。您應該添加一個using,但這無關「多瀏覽器實例」:

using(WebClient client = new WebClient()) 
{ 
    return client.DownloadString("http://abcabc.com/abc"); 
} 
2

WebClient的類在.NET Framework持有到被訪問網絡需要一定的系統資源在Microsoft Windows中堆棧。 CLR的行爲將確保這些資源最終被清理。

但是,如果您手動調用Dispose或使用using-statement,則可以在更可預測的時間清理這些資源。這可以提高較大程序的性能。

using(WebClient client = new WebClient()) 
{ 
    // Do your operations here... 
} 

你可以參考這個美麗的教程:http://www.dotnetperls.com/webclient

+0

如果可以的話,我也會在你馬克·格雷維爾之​​後馬上發佈相同的答案時給你信任。 :) – Joshua