Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AppDomain.CurrentDomain.ProcessExit and cleanup

Tags:

c#

.net

events

I have simple application when I need to stop a background thread using Stop() function before application is closed. The problem is that my Main() function has several exit points (return statements)

static void Main(string[] args)
{
/// some code
return;

// some code
return;

//// etc
}

I tried to use AppDomain.CurrentDomain.ProcessExit as a single place for clean up but it is never called (at least while there is a background thread). Is there a way to work out some nice way to implement that?

like image 572
Captain Comic Avatar asked Jan 19 '10 13:01

Captain Comic


2 Answers

You can wrap all you code in a separate method and call it from Main():

static void Main(string[] args)
{
  DoSomething();
  TerminateThread(); // Thread.Stop() code goes here
}

static void DoSomething()
{
   /// some code
   return;

   // some code
   return;

   //// etc
}
like image 64
Igor Korkhov Avatar answered Oct 13 '22 01:10

Igor Korkhov


Change the return; calls and call a cleanup routine that also terminated the process.

like image 44
Oded Avatar answered Oct 13 '22 01:10

Oded