A piece of code was brought up by someone I was talking to:
private void DownloadInformation(string id)
{
using (WebClient wc = new WebClient())
{
wc.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(DownloadStringCompleted);
wc.DownloadStringAsync(new Uri("http://www.fake.com/" + id));
}
}
The above is a simplified version of this:
(I have the author's permission to post the image.)
What bothers me about that code is that an event handler is attached, DownloadStringAsync() is called and then the using block ends, which calls Dispose() on WebClient. Is there anything that will prevent WebClient from being disposed off by using and even garbage collected prior to DownloadStringAsync() completing and DownloadStringCompleted event triggering?
There's a newer method, DownloadStringTaskAsync(), which I would think to use in conjunction with await:
private async Task DownloadInformation(string id)
{
using (WebClient wc = new WebClient())
{
wc.DownloadStringCompleted += DownloadStringCompleted;
await wc.DownloadStringTaskAsync(new Uri("http://www.fake.com/" + id));
}
}
However, even then... I would basically be betting that event triggers and handler gets called before the WebClient gets disposed off.
Am I misunderstanding the life cycle of WebClient in this scenario or is this a terrible code design?
