.NET:异步下载时是否需要保留对 WebClient 的引用?

本文介绍了.NET:异步下载时是否需要保留对 WebClient 的引用?的处理方法,对大家解决问题具有一定的参考价值

问题描述

我在一段生产代码中使用如下方法:

I use the following method in a piece of production code:

private void DownloadData(Uri uri)
{
    WebClient webClient = new WebClient();
    DownloadDataCompletedEventHandler eh = null;
    eh = delegate(object sender, DownloadDataCompletedEventArgs e)
        {
            webClient.DownloadDataCompleted -= eh;
            ((IDisposable) webClient).Dispose();
            OnDataDownloaded();
        };
    webClient.DownloadDataCompleted += eh;
    webClient.DownloadDataAsync(uri);
}

我现在担心在调用 DownloadDataCompleted 事件之前被垃圾收集的 WebClient 实例可能会导致难以重现的错误:退出我的 之后DownloadData() 方法,没有明显的对 WebClient 对象的引用,所以这可能会发生.

I am now worried that a hard to reproduce bug might be caused by the WebClient instance being garbage collected before the DownloadDataCompleted event is called: after exiting my DownloadData() method, there are no obvious references to the WebClient object, so that could plausibly happen.

所以我的问题是:这真的会发生吗?我无法重现该问题,因此可能发生了一些内部问题,阻止了 WebClient 对象被垃圾收集(例如,在等待响应时,该对象可能会在某处向全局对象注册自身).

So my question is: can this realistically happen? I can not reproduce the problem, so there might be some internal things happening that prevents the WebClient object from being garbage collected (e.g. the object might register itself with a global object somewhere while waiting for the response).

如果这有什么不同的话,代码在 .NET 2.0 上运行.

The code is running on .NET 2.0 if that makes any difference.

推荐答案

不,在回调完成之前,您的对象不会被 GC-ed.根据 垃圾收集器是否在异步期间销毁临时未引用的对象在 .NET 中调用?异步 API 保留对您的请求的引用(在异步 IO 操作所在的线程池中),因此在完成之前不会被垃圾收集."

No, your object won't be GC-ed until the callback completes. According to Does the Garbage Collector destroy temporarily unreferenced objects during async calls in .NET?, "the async API keeps a reference to your request (within the thread pool where async IO operations are lodged) and so it won't be garbage collected until it completes."

但是,您的代码也在做它不需要做的事情:您不需要分离事件处理程序,也不需要在 web 客户端上调用 Dispose.(Dispose() 实际上不是由 WebClient 实现的——您可以在 http://referencesource.microsoft.com/netframework.aspx).

But, your code is also doing stuff it doesn't need to: you don't need to detach the event handler and don't need to call Dispose on the webclient. (Dispose() is actually not implemented by WebClient-- you can can see this in the .NET Framework reference source at http://referencesource.microsoft.com/netframework.aspx).

因此,您实际上不需要在回调中引用 webclient 实例.换句话说,以下代码也可以正常工作,并避免从委托内部引用外部局部变量的任何潜在问题(如上所述).

So you don't actually need to refer to the webclient instance in your callback. In other words, the following code will work just as well, and avoid any potential issues (discussed above) of referencing external local variables from inside a delegate.

private void DownloadData(Uri uri)
{
    WebClient webClient = new WebClient();
    DownloadDataCompletedEventHandler eh = null;
    eh = delegate(object sender, DownloadDataCompletedEventArgs e)
    {
        OnDataDownloaded();
    };
    webClient.DownloadDataCompleted += eh;
    webClient.DownloadDataAsync(uri);
}

无论如何,您可能想在别处寻找错误的来源.我要看的一个地方是 HTTP 调用的结果——您可能内存不足,可能遇到服务器错误等.您可以查看 e.Error 以查看调用是否实际工作.

Anyway, you probably want to look elsewhere for the source of your bug. One place I'd look is at the results of the HTTP calls-- you may be running out of memory, may be running into server errors, etc. You can look at e.Error to see if the calls are actually working.

这篇关于.NET:异步下载时是否需要保留对 WebClient 的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1127

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1032

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this->id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:775

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this->id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:866

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:903

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:848

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:834

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:808

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1619

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1262