JoeyDiaz
JoeyDiaz

Reputation: 157

Running a Window on its own Thread

I am working on an excel add in where it takes a very long time to create the excel sheet. Because of this I am running a progress window (Winform) on its own Thread to notify the user what is going on. I am wondering if I am launch and closing the thread correctly and if I can use something better to create a thread like a task or something else. This is my code

   private static Thread tPrgBarfrm;
   private static frmProgressBar frmProgBar;

   //Launching the window
   (tPrgBarfrm = new Thread(() => System.Windows.Forms.Application.Run(new frmProgressBar()))).Start();//working

   //Update the label in the form
   frmProgBar.UpdateStatusMessage("Completed Calc Sheet");

  //Closing
  tPrgBarfrm.Abort();

Upvotes: 1

Views: 164

Answers (1)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391576

The thing that is directly wrong with your code is that you're using Thread.Abort to close the form by killing off the thread that is hosting it.

Don't do that!

There might be situations where Thread.Abort is the only option, and you need to kill that thread, but this method is there for the framework and abnormal exceptional out-there situations.

If you're designing new code where you should be able to close/terminate/exit/kill a subtask/thread, never, ever use Thread.Abort.

Instead work together with that task/thread and kindly ask it to terminate, upon which the task/thread will do that, by itself, correctly.

So how do you do that here?

Close the form.

The message loop code in Application.Run will then terminate correctly and the thread will exit normally.

So instead of keeping a reference to the thread, keep one to the form and do this:

frmPrgBar.Invoke(frmPrgBar.Close);

That is the right thing to do, and it will make all parties involved able to close down and terminate in an orderly fashion.

If you have prevented the form from being closed, you need to add in a way for you to un-prevent that when it becomes time actually to close it, a simple bool variable will help you with that.

Upvotes: 1

Related Questions