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?

4
  • 1
    Why not to refactor you Main function to have only one exit point?
    – Restuta
    Commented Jan 19, 2010 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
    Commented Jan 19, 2010 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. Commented Jan 19, 2010 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
    Commented Jan 19, 2010 at 14:22

3 Answers 3

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
}
0
2

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

2

You can use Application.ApplicationExit Event

According to MSDN the event:

Occurs when the application is about to shut down.

1
  • 6
    Only if his app is window form application. For a console application this will not work.
    – particle
    Commented Jan 19, 2010 at 14:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.