gpt4 book ai didi

F# 程序在 fsi 中正确运行,但作为 exe 挂起

转载 作者:行者123 更新时间:2023-12-04 18:59:27 24 4
gpt4 key购买 nike

我有一段代码可以在 MailboxProcessor 时向数据库添加一行收到一条消息。在 fsi 中运行时它可以正常工作,但在编译为 exe 时它会挂起。脚本如下:

#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"

编译为 exe 时,会打印“提交”,但随后挂起。如果你想尝试一下,完整代码在github here

最佳答案

似乎问题是主线程在 MailboxProcessor 之前退出。可以处理它的邮箱。 FSI 是长期存在的,所以这并没有发生在那里。我变了:

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


[<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

现在代码按照我的预期执行。

关于F# 程序在 fsi 中正确运行,但作为 exe 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41389029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com