Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

How to terminate running threads on Application shutdown?

I am writing a C# component for my client which he will consume it in a Windows Application. I start some threads in my component to achieve some background tasks but these threads keep on running even after Application is closed. My client is not taking the responsibility to call method to terminate these threads. I have to handle this shutdown in my component so what should I do?

user-image
Question added by Azmat Jadoon , Software Engineer , NADRA
Date Posted: 2013/10/30
Safwan Oyoun
by Safwan Oyoun , Software Engineer , UAS International Trip Support

you can use join(); method to terminate all threads 

// Use the Join method to block the current thread   // until the object's thread terminates. workerThread.Join();check this link from msdn :http://msdn.microsoft.com/en-us/library/7a2f3ay4(v=vs.90).aspx

Deleted user
by Deleted user

There are several options:

1. Implement the thread with a cancelation support. In the thread function, let it check for a flag continuously while it is executing for an exit. It can be a simple bool flag, a cancellation token. Simply set the flag and use the Thread.Join() to wait for it until it finishes. This is a graceful way to exit

2. Use thread.Abort() which is a terrible idea and bad practice. Use this only in an emergency situation. It's like ending a task from the task manager instead of asking the program to exit.

3. If you use a background thread or a background worker then the thread will die automatically and you don't need to do anything unless you want to wait.

 

From your question "but these threads keep on running even after Application is closed" because they are not set to be running in the background. See Thread.IsBackground

Azmat Jadoon
by Azmat Jadoon , Software Engineer , NADRA

I got the solution by capturing ApplicationExit event of Application class. It occurs when the Windows application is about to shut down.

Bowsil Ameen
by Bowsil Ameen , Sharepoint Development officer / architect , Etihad Airways

Dear Azmat,

 

can you try this steps in main block

static bool isCancellationRequested =false;staticobject gate =newobject();// request cancellationlock(gate){ isCancellationRequested =true;}// threadfor(int i =0; i <100000; i++){// simulating workThread.SpinWait(5000000);lock(gate){if(isCancellationRequested){// perform cleanup if necessary//...// terminate the operationbreak;}}}Note if your frame work is +4.0 then there is new methodhttp://msdn.microsoft.com/en-us/library/dd997364.aspxfallow the steps pls

Mubbasher Mukhtar
by Mubbasher Mukhtar , Senior Software Engineer and Researcher (Microsoft Certified Technology Specialist) , InvenSense

For a case when a number of threads are running:

 

1- Gracefull closing of threads:

 

class Global { static boolean keep_running = true; static bool running_thread_count=0; }

 

a- In your threads put a condition for execution for example: while( Global.keep_running) { do something; }

b- when you enter the thread make Global.running_thread_count++;

c- when before returing from the thread funciton: make: Global.running_thread_count--;

e- OnApplicatin Exit, mark Global.keep_running = false;

Then wait for the Threads to exit, like this:

 

while(Global.running_thread_count>0);

//In this while loop you can further check if it is taking too long etc...

 

2- Forecull Exit... Application.Exit(); will do that...

 

3- Thread collection, keep handle to each thead and close them one by one before exiting ...

 

Daanish Rumani
by Daanish Rumani , Product Manager , Publicis Sapient

Use background threads by setting the  IsBackground property on the threads that you create. You do not have to do anything extra to ensure that the threads die when the application exits. But beware that the threads would be killed and you would not get any chance to cleanup resources.

 

However if you need to cleanup your resources then you would need to tap into an event that is fired when your component is about to be unloaded and do three things:

  1. Set a flag (a boolean variable) on each thread to indicate it needs to end
  2. code each thread to periodically check for this flag and exit when it is true
  3. Call join on each thread so that the event handler does not return until all threads have gracefully exited

 

More Questions Like This