I would like to have a certain function executed when a console application exits. I have found many solutions but none of them work for me. Why the following code does not display CancelKeyPress etc?
printfn "Starting a Test"
System.Console.ReadLine() |> ignore
System.Console.CancelKeyPress.Add (fun _ -> printfn "CancelKeyPress" )
System.AppDomain.CurrentDomain.ProcessExit.Add (fun _ -> printfn "ProcessExit" )
System.AppDomain.CurrentDomain.DomainUnload.Add (fun _ -> printfn "DomainUnload" )
I have slightly modified my code and added the try finally statement but without any luck. I run the application and then hit “ctrl + c” or click on “Close button”
let write v = System.IO.File.AppendAllText("test.txt", v + "\n")
try
write "Starting a Test 2"
System.Console.ReadLine() |> ignore
System.Console.CancelKeyPress.Add (fun _ -> write "CancelKeyPress" )
System.AppDomain.CurrentDomain.ProcessExit.Add (fun _ -> write "ProcessExit" )
System.AppDomain.CurrentDomain.DomainUnload.Add (fun _ -> write "DomainUnload" )
finally
write "Try Finally"
When I run your example it prints “ProcessExit”, so that one works. The reason why “CancelKeyPress” is not printed is because the application probably terminates before it occurs (And you also need to register the handler before the
ReadLine). The following will cancel first 10Ctrl + Cpresses and then exit on the next one:Anyway one straightforward option that should work would be to wrap the whole
mainfunction insidetry .. finally. Something like:EDIT When I run your second example, I get a file with:
I’m not sure why the
DomainUnloadedhasn’t been printed, but the remaining should work as expected.