• 0

[C#] Closing Forms


Question

Hey all,

I have a little simple application.. i am running a form, it spawns a thread. When i hit the close button (X) then it disappears, but the program does not close as the thread is still running.

I have come up with a solution to this, where the thread checks if the form is visible or not, if it is not visible, then closes everything. But because the thread only does its job once every 30 seconds, the program may not be cleared for a while.

Is there a more efficient way of doing this?

Thanks in advance,

David.

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

What about using Application.Exit()? That should terminate the application. You could have it perform this action in the FormClosing event.

Steven

Link to comment
Share on other sites

  • 0

Also, sometimes when debugging, you'll come across an uncaught exception when you run Application.Exit() as well, because the thread has not finished whatever it was doing. Just make sure you end the thread's actions properly, and just finish whatever you were doing in that thread :)

Link to comment
Share on other sites

  • 0

If it doesn't matter that the thread dies a sudden death, just kill the process and the thread will go along with it.

If you need for the thread to clean up, wrap up, etc., you have lots of options here. If the thread is busy all the time, you can just have the thread check if the form is still alive in its work loop (to reduce the cost of this, have the thread check a shared variable or memory location instead of looking for the actual window). Or if your thread will not be busy the whole time, then you can signal to the thread that the window is dying by sending a thread message or signaling a synchronization object.

Link to comment
Share on other sites

  • 0

Select on the form, right next to properties, click on the lightning icon (events), then look for form closing. You can try use Environment.Exit() to make sure the program terminates after you click on the X button.

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.