2

I have a process written in C# which has no forms or output whatsoever.

static void Main() {
    MyBackgroundProcess process = new MyBackgroundProcess();
    // begin background process
    process.Start(); 
    // keep application running in the background, run events
    Application.Run();
}

I need to free up some resources and do other things when the application terminates (which should only be when the user running it logs off or if it's manually killed through the task manager; the process will never terminate itself).

What's the best way to handle this?

Things I've tried that haven't worked:

  • Hooking an event to both Application.ApplicationExit and Application.ThreadExit
  • Had MyBackgroundProcess implement IDisposable and wrapped the Main logic in a using()
MisterZimbu
  • 2,673
  • 3
  • 27
  • 28

4 Answers4

2

If MyBackgroundProcess inherits System.Diagnostics.Process, then there are events that are useful to you.

You can tap into the Exited event of the process object to execute a method when the process terminates. Take a look at the docs for details:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx

kbrimington
  • 25,142
  • 5
  • 62
  • 74
2

This one can help you:

C# - Deallocate resources on process termination

Community
  • 1
  • 1
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
  • I ended up using one of the "workarounds" in there (using a monitoring process to perodically check, which in my case, already existed). Ironically enough one of the main cleanup functions that I wanted to do was to tell the monitoring service that this process was no longer running. Thanks! – MisterZimbu Aug 06 '10 at 17:26
1

You simply cannot make this reliable. Taskmgr shoots you in the head without recourse. The more obvious failure modes are some kind of nasty CLR problem like ExecutionEngineException. And the simple stuff like somebody tripping over the power cord.

Solve this by setting a persisted flag at normal shutdown, after the Application.Run() call, that indicates "data is known-good". Always check at startup if the previous run was bad (missing the flag) so you can clean up the shrapnel.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

You could use a meta process of sorts, i.e. introduce a third process that runs both the main process and the background process, and then kills the background process if the main process terminates.

Some pseudo code:

static void Main()
{
  MyBackgroundProcess backgroundProcess = new MyBackgroundProcess();                
  backgroundProcess.Start(); 

  MyMainProcess mainProcess = new MyMainProcess();
  mainProcess.Start();

  mainProcess.WaitForExit();
  backgroundProcess.Kill();
}
Mhmmd
  • 1,483
  • 9
  • 15