.NET: Do I need to keep a reference to WebClient while downloading asynchronously?

后端 未结 5 1007
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 21:54

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

private void DownloadData(Uri uri)
{
    WebClient webClient = new WebClient();
    DownloadDataCom         


        
5条回答
  •  再見小時候
    2020-12-14 22:26

    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."

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

    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);
    }
    

    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.

提交回复
热议问题