9

Subject says it all.

I want some code to run if my application is terminated by, say, ^C.

Brian
  • 117,631
  • 17
  • 236
  • 300
Paul Steckler
  • 617
  • 5
  • 19
  • Just a thought--although you're asking about F# you could probably google for ".Net Application Termination Event" and find more information on the general question of how to handle this sort of issue properly. – Onorio Catenacci Jul 30 '10 at 12:46

2 Answers2

5

Use AppDomain.ProcessExit (http://msdn.microsoft.com/en-us/library/system.appdomain.processexit.aspx):

System.AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> ...)
Thomas
  • 10,933
  • 14
  • 65
  • 136
Dmitry Lomov
  • 1,406
  • 8
  • 8
  • 1
    Maybe ProcessExit (http://msdn.microsoft.com/en-us/library/system.appdomain.processexit.aspx) will be more suitable for case of normal process termination. In simple console example System.AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> printfn "ProcessExit") System.AppDomain.CurrentDomain.DomainUnload.Add(fun _ -> printfn "DomainUnload") it outputs "ProcessExit" after exit. – desco Jul 30 '10 at 08:44
  • Absolutely! How could I miss it? – Dmitry Lomov Jul 30 '10 at 20:49
1

See code below. To handle Ctrl-C in a console app, use the Console.CancelKeyPress event.

// does not work - no exception on Ctrl-C
//System.AppDomain.CurrentDomain.UnhandledException.Add(
//    fun _ -> printfn "app is about to die")

System.Console.CancelKeyPress.Add(
    fun _ -> printfn "app is about to die")
printfn "starting..."
System.Threading.Thread.Sleep(5000)  // press Ctrl-C
printfn "ended"
Brian
  • 117,631
  • 17
  • 236
  • 300