0

Say I have a form that is performing a bulk file copy. I have written an async method to do this work, and have successfully implemented a cancellation process, using a cancellation token. Part of the cancellation is to delete all the files currently copied, prior to leaving the Task.

This works fine if the user clicks the Cancel button. However in cases where the user closes the form, I cannot find a way to wait on the underlying Task before progressing with the rest of the Form closing procedure. As such, the Task is terminated, and the clean up does not occur.

Can anyone recommend a pattern for preventing the form from closing prior to all awaited threads completing?

pixelbadger
  • 1,556
  • 9
  • 24
  • Hook into the form's OnClose event? http://msdn.microsoft.com/en-us/library/system.windows.forms.form.closing(v=vs.110).aspx for WinForm or http://msdn.microsoft.com/en-us/library/system.windows.window.onclosing.aspx for WPF – Pete Garafano May 19 '14 at 14:19
  • 2
    Instead of trying to wait on the task and freeze the UI, prevent the form from closing if the task is still running, by setting `Cancel=true`, eg `args.Cancel = !myTask.IsCompleted;` – Panagiotis Kanavos May 19 '14 at 14:20
  • @PeteGarafano there's no `OnClose` event, you probably mean `FormClosed`. It doesn't matter though as the method simply raises the event, but the form is already closed at this point. – Panagiotis Kanavos May 19 '14 at 14:21
  • 1
    @PanagiotisKanavos I meant Form.FormClosing, not Form.FormClosed. This event can be used to even cancel the form closing. http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing(v=vs.110).aspx – Pete Garafano May 19 '14 at 14:29
  • 1
    Same [as this](http://stackoverflow.com/questions/1731384/how-to-stop-backgroundworker-on-forms-closing-event/1732361#1732361). You of course can't skip really closing the form when the task completes. – Hans Passant May 19 '14 at 15:04

0 Answers0