我寫爲Windows Phone 7 Silverlight應用程序,其具有需要進行多次請求WebClient.DownloadStringAsync()如果WebClient的情況下,在Silverlight
是一個類被重用我最好創建Web客戶端的一個新實例每個請求,還是在字段中初始化單個實例並將其用於每個請求(確保一次只有一個請求活動)更高效?
public class MainViewModel : INotifyPropertyChanged
{
private readonly WebClient _wc;
public MainViewModel()
{
_wc = new WebClient
{
Credentials = new NetworkCredential("yyyyyyy", @"xxxxxx")
};
}
readonly Uri _baseUrl = new Uri(@"https://some.web.url");
public void GetServices()
{
_wc.DownloadStringCompleted += GetServicesCompleted;
var uri = new Uri(_baseUrl, "/path");
_wc.DownloadStringAsync(uri);
}
private void GetServicesCompleted(object sender, DownloadStringCompletedEventArgs e)
{
_wc.DownloadStringCompleted -= GetServicesCompleted;
string result = e.Result;
// other logic...
GetServiceResources();
}
private void GetServiceResources()
{
_wc.DownloadStringCompleted += GetServicesResourcesDownloaded;
var url = new Uri(_baseUrl, "/path2");
_wc.DownloadStringAsync(url);
}
// etc
}
我知道你在談論關於脾氣暴躁的狀態WCF代理可以讓自己進入!知道它是否與Silverlight的WebClient相似也會很有趣。 – 2010-12-14 22:37:58
@BFree已經刪除了他的答案,但只是重複說明Silverlight的WebClient類中沒有Dispose()方法,所以在這裏使用塊不相關。 – 2010-12-15 03:58:21
然而,作爲一種個人偏好,如果容易這樣做或者記錄第一次發生,我會添加em - 總是處置任何'IDisposable'是一種好習慣;即使是WebClient也沒有什麼不好的。 – 2010-12-15 10:18:29