F # program works correctly in fsi, but hangs like exe

I have a piece of code that adds a row to the database when MailboxProcessor receives a message. It works correctly when running in fsi, but it freezes when compiling in exe. The script looks like this:

 #r "../packages/Newtonsoft.Json/lib/net40/Newtonsoft.Json.dll" #r "../packages/SQLProvider/lib/FSharp.Data.SqlProvider.dll" open Newtonsoft.Json open FSharp.Data.Sql open System let [<Literal>] ResolutionPath = __SOURCE_DIRECTORY__ + "/../build/" let [<Literal>] ConnectionString = "Data Source=" + __SOURCE_DIRECTORY__ + @"/test.db;Version=3" // test.db is initialized as follows: // // BEGIN TRANSACTION; // CREATE TABLE "Events" ( // `id`INTEGER PRIMARY KEY AUTOINCREMENT, // `timestamp` DATETIME NOT NULL // ); // COMMIT; type Sql = SqlDataProvider< ConnectionString = ConnectionString, DatabaseVendor = Common.DatabaseProviderTypes.SQLITE, ResolutionPath = ResolutionPath, IndividualsAmount = 1000, UseOptionTypes = true > let ctx = Sql.GetDataContext() let agent = MailboxProcessor.Start(fun (inbox:MailboxProcessor<String>) -> let rec loop() = async { let! msg = inbox.Receive() match msg with | _ -> let row = ctx.Main.Events.Create() row.Timestamp <- DateTime.Now printfn "Submitting" ctx.SubmitUpdates() printfn "Submitted" return! loop() } loop() ) agent.Post "Hello" 

When compiling in exe, "Submit" is printed, but then it freezes. If you want to try, the full code is on github here

+5
source share
1 answer

It seems that the problem was that the main thread exited before MailboxProcessor could process its mailbox. FSI is durable, and this did not happen there. I changed:

 [<EntryPoint>] let main argv = agent.Post "Hello" agent.Post "Hello again" 0 

to

 [<EntryPoint>] let main argv = agent.Post "Hello" agent.Post "Hello again" let waitLoop = async { while agent.CurrentQueueLength > 0 do printfn "Sleeping" do! Async.Sleep 1000 } Async.RunSynchronously waitLoop 0 

and now the code is executing, as I expected.

+5
source

Source: https://habr.com/ru/post/1262062/


All Articles