简体   繁体   中英

Error while closing form that is running a BackGround Thread

First time , i write an application that is running a foreground (defult) thread :

t = new Thread(new ThreadStart(GenerateRandom));
t.Start();

And when i close my form while running thread , it crashes , and throw an exception . after some search ( How to close all running threads? ), i founded that a foreground thread keeps running after closing main and i have to set my thread to background , so i do somthing like this :

t = new Thread(new ThreadStart(GenerateRandom));
t.IsBackground = true;
t.Start();

but it still throwing exception and i cant close mhy form while running my thread !!!

And i don't khow WHY ?!

I tried some solutions in FormClosing event :

  1. Use : Enviroment.Exit(Enviroment.ExitCode);
  2. Use : thread.Abort();

First one doesen't worked , and Second on one crashes when i close form befor running thread .

here is some pictures of my program :

Picture 1 , Befor closing form : Befor截止表格

Picture 2 , after push the Close Button : 截止后表格

Thank you all .

Did you see the exception message FormatException . Would have you search with that name you would have got the idea. It has no relation with your running thread. It's occurring cause, the entered text is not a number and thus trying to parse it as Int failing with that exception.

Usually you run your background job UNTIL the form is closed.

Something like:

void myThreadJob()
{
   while (!IsDisposed)
   {
      // do my "infinite" task until the form is disposed
   }
}

Another method is having a boolean field in your form. When your form is closed, set the field to true in FormClosing event. You then check the boolean field status in the while loop in thread code.

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