简体   繁体   中英

What happens to outstanding .NET WebClient async operations when WinForm app closes?

I am trying to understand, what exactly happens to WebClient outstanding Async operations when WinForms app is closed. I do not actually have a problem, my question is driven by desire to understand the exact flow.

The app uses the following pattern, when download requested:

        using (WebClient wc = new WebClient())
        {
                wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(my_DownloadProgressChanged);
                wc.DownloadFileCompleted += new AsyncCompletedEventHandler(my_DownloadFileCompleted);

Event handlers are methods on a Form. One of the concerns I have is I do not want those to get invoked when form is closed already. I could keep references to WebClient, and -= on form close, but I'd like to not do unnecessary work to avoid new problems.

Here are questions I have:

  • why is it ok to Dispose WebClient before Async operations complete?
  • do we have to unregister handlers on main window shutdown, and what happens if we don't? my observation, is that if I close form, none of Async callbacks are invoked, but why exactly, how exactly does it shutdown?

I reviewed WebClient code but I couldn't figure this stuff out. Thanks in advance.

why is it ok to Dispose WebClient before Async operations complete?

Looking at the Reference Source for WebClient, it doesn't look like it actually has any specific implementation for the Dispose method. It shouldn't be safe to dispose any IDisposable and expect async operations to finish successfully, but in this case it might happen to work because disposing the web client doesn't do anything to abort the open connections.

As to your question about what happens when the application exits, the operating system will terminate any open connections when the process ends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM