假设我有这个函数,可以从主线程中多次调用。每次调用它时,我都会创建一个WebClient
对象来异步下载一些数据。
我的问题......这样做安全吗?调用事件后是否释放WebClient
对象?如果它不会自动释放,我不想继续分配内存。
我的应用程序适用于带Silverlight的WP7。
谢谢!
void DownloadData(string cURL)
{
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted +=
new System.Net.DownloadStringCompletedEventHandler(
webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(cURL));
}
static void webClient_DownloadStringCompleted(object sender,
System.Net.DownloadStringCompletedEventArgs e)
{
...
}
答案 0 :(得分:4)
SilverLight version of WebClient
未实现IDisposable
。你做对了 - 时间到了,webClient
会自动被垃圾收集。
答案 1 :(得分:4)
您可以将其放入使用块中,而不是手动处理WebClient。
using (WebClient webClient = new WebClient())
{
// Your business in here...
}
答案 2 :(得分:1)
我看到了2个问题。首先,webclient不会在所有可能的情况下处理,其次会保留对WebClient的引用,因为您从未取消订阅该事件。
我认为这接近它(尽管仍然不完美,想想ThreadAborted):
void DownloadData(string cURL)
{
WebClient webClient = new WebClient();
try
{
webClient.DownloadStringCompleted += new System.Net.DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
webClient.DownloadStringAsync(new Uri(cURL));
}
catch
{
webClient.Dispose();
throw;
}
}
static void webClient_DownloadStringCompleted(object sender, System.Net.DownloadStringCompletedEventArgs e)
{
WebClient webClient = (WebClient)sender;
webClient.DownloadStringCompleted -= webClient_DownloadStringCompleted;
try
{
}
finally
{
webClient.Dispose();
}
}
答案 3 :(得分:-3)
WebClient没有实现iDisposable接口,因此没有什么特别需要做的事情来允许正确的垃圾收集。当CLR检测到对象没有当前引用时,它将被安排进行垃圾回收。当然你不知道什么时候会发生,所以内存可能会或可能不会(很可能不会)立即被释放。