6

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?

RJFalconer
  • 10,890
  • 5
  • 51
  • 66
Captain Comic
  • 15,744
  • 43
  • 110
  • 148
  • 1
    Why not to refactor you Main function to have only one exit point? – Restuta Jan 19 '10 at 13:52
  • 2
    Are you asking how you can optimize to have a single point of exit, or do you want to be able to kill your process and all its background threads at a given moment? – Abel Jan 19 '10 at 13:55
  • 1
    It is never called because your thread is still running, keeping the process alive. That was covered in your previous question. – Hans Passant Jan 19 '10 at 14:03
  • 1
    This line in SystemEvents.cs/1540 keep our application in wait state UnsafeNativeMethods.MsgWaitForMultipleObjectsEx(0, IntPtr.Zero, 100, NativeMethods.QS_ALLINPUT, NativeMethods.MWMO_INPUTAVAILABLE) and there is no event fired before it. So bottom line that you should fix you code to get a single point of return instead. – particle Jan 19 '10 at 14:22

3 Answers3

5

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
}
Igor Korkhov
  • 8,283
  • 1
  • 26
  • 31
2

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

Oded
  • 489,969
  • 99
  • 883
  • 1,009
2

You can use Application.ApplicationExit Event

According to MSDN the event:

Occurs when the application is about to shut down.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Giorgi
  • 30,270
  • 13
  • 89
  • 125