Live Chat Icon For mobile
Live Chat Icon

How to display a status dialog in a background thread during a long operation and allow the user to cancel?

Platform: WinForms| Category: Patterns

You can do this by starting a new thread and executing Application.Run for the status dialog form when the background thread starts running. To communicate changes in percentage use BeginInvoke to executes a specific delegate asynchronously on the thread that the form was created on.

Download the ProgressThread progressthread.zip sample for a complete implementation of a BackgroundThreadStatusDialog class that shows a status dialog in a separate thread.

In order to use BackgroundThreadStatusDialog from your code you have to update the Progress inside your loop and check the IsCanceled state to detect if the user pressed the Cancel button.


    private void button1_Click(object sender, System.EventArgs e)
    {
      BackgroundThreadStatusDialog statusDialog = new BackgroundThreadStatusDialog();
      try
      {
        for (int n = 0; n < 1000; n++)
        {
          statusDialog.Percent = n/10;
          int ticks = System.Environment.TickCount;
          while (System.Environment.TickCount - ticks < 10)
            ;
          if (statusDialog.IsCanceled)
            return;
        }
        statusDialog.Close();
        MessageBox.Show(statusDialog.IsCanceled ? ''Canceled'' : ''Success'');
      }
      finally
      {
        statusDialog.Close();
      }
    }

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.