Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly close a C# application that has created multiple threads?

I am writing a GUI application.

The application is opening multiple threads during it's life time. One of the threads is handling events that can come from other applications, so it is waiting in a while(true) loop for the event which is never been terminated.

The user can close the application in any minute. I want to close all the threads that the main application had opened.

I am using Process.GetCurrentProcess().Kill(); to deal with this problem at the moment.

Is this a good solution? If not, why and what is the proper way to deal with this problem, how to close all threads that were opened by the main application?

like image 302
Alex Avatar asked Oct 15 '10 18:10

Alex


People also ask

What happens when you close AC corporation?

A traditional corporation, commonly referred to as a C corporation, is owned by its shareholders. When a C corporation shuts down, any cash that's left over must be distributed to those shareholders.

What is the first step that must be taken to terminate a corporation?

The first step in dissolving a corporation usually involves having your board of directors and shareholders vote to approve the dissolution. Under most state rules, you start by holding a meeting of the board of directors to vote on a resolution to approve the dissolution of the corporation.


2 Answers

If you create the new threads as background threads (by setting IsBackground before starting them), they will automatically stop when the main thread (the application thread) terminates.

(From MSDN):

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

like image 112
adrianbanks Avatar answered Oct 23 '22 10:10

adrianbanks


Once you already have threads waiting for some events, just add one more event that when triggered will instruct the thread to terminate.

In case you don't need to provide some means of graceful shutdown for other threads, you can switch them into the “background thread” mode to ensure automatic termination — see MSDN for a thorough discussion of this topic.

like image 45
Ondrej Tucny Avatar answered Oct 23 '22 10:10

Ondrej Tucny