简体   繁体   中英

closing main from another thread

I am trying to close the appliaction some how when another thread finishes. I am using c#. code below is just an example

class main
{
  constuctor
  {
    thread t = new thread(open loading screen);

  }

  public void open loading screen()
  {
    if (error) 
     exit program
      application.exit(); // doesn't work
     this.Close; // doesn't work
    thread.abort or mainform.abort doesnt work.
  }
}

if i call a function on the main with application.exit this doesnt work because the call is made from another thread.

so how do I exit the program??

thanks in advance

The worker thread should set a variable or signal an event of some kind that the main thread should periodically check - it can shut down in the normal fashion when it is able.

Use IsAlive in the main thread to check if the other thread(s) have ended and then exit if they have.

http://www.java2s.com/Code/CSharp/Thread/UseIsAlivetowaitforthreadstoend.htm

Use the background worker class instead of an ordinary thread. The backgroundworker can be used to do work in another thread than the UI thread. It also has some handy events that can be used to send progress updates back to the "owning" thread. Take a look at:

ProgressChanged and RunWorkerCompleted

Here the solution in one line of code

mainForm.Invoke((MethodInvoker)(() => mainForm.Close()));

have a Closing event in mainform that closes the thread if it doesnt close by it self after this

after a lot of head scathing i think I have made some progress. I am not 100% sure but Can you exit an application before the constructor is finished and the main form loaded?

constuctor  {    thread t = new thread(open loading screen);  }

I do the exact same thing with a exit screen using a variable between the main for and another one. and I have an application exit in the main for if it returns true.

At the start I have a loading screen but the main form isnt loaded yet and the call has been made from the constructor and the construtor hasn't finished yet.

And one more thing should all the thread/ class / loading // program setup be done in the main constructor or some other way if so please advise.

thanks

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