How to exit all running threads?

后端 未结 6 1827
有刺的猬
有刺的猬 2020-12-02 20:02

The following code does not exit the application. How can I exit the application and make sure all the running threads are closed?

foreach (Form form in Appl         


        
6条回答
  •  萌比男神i
    2020-12-02 20:21

    I went through a similar issue in my software, but unfortunately just making the threads to work in background didn't solve the issue. In fact while the thread brings back data (the main software is data driven) and if I close the application, it results to Windows Error, giving rise to a debugging message.

    So what actually worked for me:

    Step 1: Made all threads run in background such as

    Thread aThread = new Thread(MethodName);
    aThread.IsBackground = true; //<-- Set the thread to work in background
    aThread.Start();
    

    Step 2: In the closing action of the form/application call the Environment.Exit method, such as

    Environment.Exit(Environment.ExitCode);
    

    This kept the memory managed perfectly, with no memory leak.

    Hope this helps.

提交回复
热议问题