gpt4 book ai didi

.net - F#-将Task 转换为普通任务

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

由于我需要与Discord.NET库实现互操作性,因此我正在使用Giraffe通过异步工作流创建 native .NET任务。我有一个需要使用Task的事件,但是我正在编写的事件处理程序返回一个Task<unit>,并且由于某种原因类型检查器不够聪明,无法意识到这是同一件事。有没有一种方法可以将Task<unit>转换为简单的Task

这是我的代码:

let messageReceived (msg : SocketMessage) =
task {
let author = msg.Author.Username
let text = msg.Content
match msg.Author.Username with
| "Monika" -> ()
| usr ->
if text.ToLower().StartsWith "<@407367655830585344> say" then
text.Substring 26 |> msg.Channel.SendMessageAsync |> ignore
else if text.ToLower().StartsWith "<@407367655830585344>" then
let response = (Lines.VoiceLines |> Extras.randomElement).Replace("[player]", author)
msg.Channel.SendMessageAsync response |> ignore
else if text.ToLower().StartsWith "delete" then
text.Substring 7 + ".chr deleted" |> msg.Channel.SendMessageAsync |> ignore
else if Extras.onein 10 then
let response = (Lines.VoiceLines |> Extras.randomElement).Replace("[player]", author)
msg.Channel.SendMessageAsync response |> ignore
}

_client.add_MessageReceived (fun m -> messageReceived m)

最后一行产生一个错误,说 MessageReceived事件需要一个带有签名 SocketMessage -> Task的函数:

error FS0001: This expression was expected to have type 'Task' but here has type 'Task<unit>'

最佳答案

TaskTask<T>的基类,因此您应该能够使用Task<unit>运算符将Task升级为:>。尝试这样的事情:

(fun m -> messageReceived m :> Task)

我认为这个最小的例子重现了这个问题:
// int -> Task<unit>
let sleepTaskT (m : int) = Async.Sleep m |> Async.StartAsTask
// (int -> Task) -> Task
let foo (f : int -> Task) = f 1000
// "This expression was expected to have type 'Task' but here has type 'Task<unit>'"
foo (fun m -> sleepTaskT m)
// this works by explicitly upcasting sleepTaskT's Task<unit> to Task
foo (fun m -> sleepTaskT m :> Task)

关于.net - F#-将Task <unit>转换为普通任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48553068/

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