C# Forms modal dialog, background task, cancel button RRS feed

  • Question

  • Hi all;

    I want to put up a modal dialog box that has a progress bar, status text, and cancel button. I want this dialog to have a background task that is reading a bunch of records from a database - multiple selects.

    For each select I want to update the status text to say what I'm on. If the user clicks cancel, I want to stop before I make the next query and exit.

    When it cancels, I'd prefer to cancel the task and then forget about it - fine if it takes 30 seconds to get to a cancellable point. And return immediately from the ShowDialog() call.

    I'm not asking about the read from the database part, just how do I code up a dialog with a background task where I can cancel the task from a button in the dialog and when the task completes, the dialog exits.

    I think I know how to do this (I've done it before with background worker threads), but I want to learn the proper way to do this using tasks and cancellation tokens. This is close but not all of what I need.

    thanks - dave

    What we did for the last 6 months - Made the world's coolest reporting & docgen system even more amazing

    Sunday, December 29, 2019 12:46 PM

All replies

  • This can be done with TaskDialogIndirect (P/Invoke)

    Sunday, December 29, 2019 3:01 PM
  • First, this should be in the forum for the relevant UI; probably either Windows Forms or WPF. 

    I think you can do it with a BackgroundWorker and an AutoResetEvent. From the background task you can report progress and the progress event handler will execute in the task that created the BackgroundWorker, the dialog in this case. Also in the dialog create an AutoResetEvent and in the task check the event when possible, such as between selects. In the dialog's cancel button handler set the event. Let us know if you need details.

    The StackOverflow question and answer create the task using the Task class and use async and await. Many developers prefer that but I usually do not. Also the question seems to require that the task be created outside the dialog but I think it would be simpler to create the task in the dialog if that satisfies requirements.

    Sam Hobbs

    Sunday, December 29, 2019 8:10 PM