title: .NET: Do I need to keep a reference to WebClient while downloading asynchronously?
body: <p>I use the following method in a piece of production code:</p>
  
  <pre><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);
  }
  </code></pre>
  
  <p>I am now worried that a hard to reproduce bug might be caused by the <code>WebClient</code> instance being garbage collected before the <code>DownloadDataCompleted</code> event is called: after exiting my <code>DownloadData()</code> method, there are no obvious references to the <code>WebClient</code> object, so that could plausibly happen.</p>
  
  <p>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 <code>WebClient</code> object from being garbage collected (e.g. the object might register itself with a global object somewhere while waiting for the response).</p>
  
  <p>The code is running on .NET 2.0 if that makes any difference.</p>