开发者

Console onExit events using F#

开发者 https://www.devze.com 2023-02-05 02:37 出处:网络
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?

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.Domai开发者_StackOverflownUnload.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 10 Ctrl + C presses and then exit on the next one:

Console.CancelKeyPress.Add(fun arg -> 
  printfn "CancelKeyPress"; arg.Cancel <- true ) 
for i in 0 .. 10 do 
  System.Console.ReadLine() |> ignore 

Anyway one straightforward option that should work would be to wrap the whole main function inside try .. finally. Something like:

let main (args) = 
  try
    // run the application
  finally
    // finalization code here

EDIT When I run your second example, I get a file with:

Starting a Test 2
Try Finally
ProcessExit

I'm not sure why the DomainUnloaded hasn't been printed, but the remaining should work as expected.

0

精彩评论

暂无评论...
验证码 换一张
取 消