将一个对象被其预约引发异步事件后自动处理? [英] Will an object be disposed automatically after an asynchronous event it subscribed to is raised?

查看:124
本文介绍了将一个对象被其预约引发异步事件后自动处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我有这个功能,可以从主线程调用多次。每到这个被调用时,我创建了一个 Web客户端对象异步下载一些数据。

我的问题...这是安全的呢?在 Web客户端对象事件被称为后释放?我不喜欢保持如果不打算就被自动释放内存分配。

我的应用是与Silverlight WP7。

谢谢!

 无效DownloadData(字符串卷曲)
{
    Web客户端Web客户端=新的WebClient();
    webClient.DownloadStringCompleted + =
       新System.Net.DownloadStringCompletedEventHandler(
            webClient_DownloadStringCompleted);
    webClient.DownloadStringAsync(新的URI(卷曲));
}静态无效webClient_DownloadStringCompleted(对象发件人,
                      System.Net.DownloadStringCompletedEventArgs五)
{
    ...
}


解决方案

Web客户端不实现IDisposable接口,所以没有什么特别需要做,以便正确的垃圾收集。当CLR检测到有对象没有当前引用,会定期进行垃圾回收。当然,你不知道何时会发生这样的内存可能会或可能不会(很可能不是)被释放立即生效。

Let's suppose I have this function that can be called several times from the main thread. Every time this is called, I create a WebClient object to download some data asynchronously.

My question... is this safe to do? Is the WebClient object released after the event is called? I wouldn't like to keep allocating memory if it is not going to be freed automatically.

My application is for WP7 with Silverlight.

Thanks!

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)
{
    ...
}

解决方案

WebClient does not implement the iDisposable interface so there is nothing special that needs to be done to allow for proper garbage collection. When the CLR detects that there are no current references to the object, it will be scheduled for garbage collection. Of course you don't know just when that will occur so the memory may or may not (most likely not) be freed up immediately.

这篇关于将一个对象被其预约引发异步事件后自动处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆