简体   繁体   中英

How do I write an exit handler for an F# application?

Subject says it all.

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

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

System.AppDomain.CurrentDomain.ProcessExit.Add(fun _ -> ...)

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM