0

My WinForm application contain many loops that takes time to complete, and many times when I click the X to close the form (and the application) I can see that the application is still running in the background, and I also see it in the Task-Manager.

What is the best way to exit all loops and threads in a clean way when the user is closing the main form?

Should I plant:

if (userPressedClose == true)
    break;

in every loop and thread that I have in my application? It looks to me like an ugly solution…

Is there a simple way to ask the application to stop all loops and threads automatically, and end the application in a clean way?

LarsTech
  • 80,625
  • 14
  • 153
  • 225
Robert
  • 13
  • 5
  • Related: [How to force exit application in C#?](https://stackoverflow.com/questions/7971315/how-to-force-exit-application-in-c) – Theodor Zoulias Aug 28 '22 at 21:28
  • Sounds like you need to use Tasks with `async` `await` and a `CancellationToken`. Then when you exit you simply cancel the token and all the code stops. – Charlieface Aug 28 '22 at 23:55
  • Are these loops run asynchronously at the same time? – T.S. Aug 29 '22 at 01:59
  • @T.S Yes, there are several threads that runs in the background at the same time. – Robert Aug 29 '22 at 02:36
  • @ Theodor Zoulias Thanks, I used Enviroment.Exit(0); – Robert Aug 29 '22 at 02:38
  • If you have threads, run as tasks than Use cancellation token. use `onformclosing` even to set `cancel=true` on the token and all the loops will go away – T.S. Aug 29 '22 at 02:38
  • @T.S I don’t know this commands, I will have to read about it and see how to use it. But my new problem is that the FormClosing() event is not firing… I have to click several times on the Form’s X icon until it reaches there… – Robert Aug 29 '22 at 02:44

0 Answers0