我想返回一个HttpResponseMessage,它IDisposable在 a Result(或任何其他受歧视的联合)内实现 , 。然而,由于Result它本身不是 IDisposable,所以我不能use!像一次性对象本身那样。我该怎么办?我可以实现我自己的 DU(称为DisposableResult实现IDisposable自身)吗?
下面是我的意思的一个例子。crawlStuff异步返回Result<HttpResponseMessage, string>。我无法use!得到结果,导致内存泄漏,除非我手动释放它。
open System.Net.Http
let crawlStuff (client : HttpClient) : Async<Result<HttpResponseMessage, string>> =
async {
// res is HttpResponseMessage which implements IDisposable
let! res = client.GetAsync("https://ifconfig.me") |> Async.AwaitTask
return
if res.IsSuccessStatusCode then
Ok res
else
Error "Something wrong"
}
async {
use client = new HttpClient()
// Memory leak because result it could carry HttpResponseMessage.
// I want to use! here, but can't because Result<> is not IDisposable
let! response = crawlStuff client
printfn "%A" response
} |> Async.RunSynchronously
Run Code Online (Sandbox Code Playgroud)
我会创建围绕 的包装器Result,它将处理底层值:
let (|AsDisposable|) x =
match box x with
| :? IDisposable as dis -> ValueSome dis
| _ -> ValueNone
type ResultDisposer<'v, 'e> =
struct
val Result : Result<'v, 'e>
new res = { Result = res }
interface IDisposable with
member r.Dispose() =
match r.Result with
// | Ok (:? IDisposable as dis) // causes FS0008, so we have to hack
| Ok (AsDisposable (ValueSome dis))
| Error (AsDisposable (ValueSome dis)) -> dis.Dispose()
| _ -> ()
end
type Result<'a, 'b> with
member r.AsDisposable = new ResultDisposer<'a, 'b>(r)
Run Code Online (Sandbox Code Playgroud)
并以这种方式使用它
async {
use client = new HttpClient()
let! response = crawlStuff client
use _ = response.AsDisposable
printfn "%A" response
} |> Async.RunSynchronously
Run Code Online (Sandbox Code Playgroud)
此解决方案避免了重写现有代码的需要DisposableResult,并避免了当一次性值是引用类型时的分配,例如HttpResponseMessage. 但反编译显示 F# 框ResultDisposer,即使它不应该:(
是的,您可以实现自己的一次性结果类型,如下所示:
type DisposableResult<'t, 'terr when 't :> IDisposable> =
| DOk of 't
| DError of 'terr
interface IDisposable with
member this.Dispose() =
match this with
| DOk value -> value.Dispose()
| _ -> ()
Run Code Online (Sandbox Code Playgroud)
那么用法将是:
open System.Net.Http
let crawlStuff (client : HttpClient) : Async<Result<HttpResponseMessage, string>> =
async {
// res is HttpResponseMessage which implements IDisposable
let! res = client.GetAsync("https://ifconfig.me") |> Async.AwaitTask
return
if res.IsSuccessStatusCode then
DOk res
else
DError "Something wrong"
}
async {
use client = new HttpClient()
use! response = crawlStuff client
printfn "%A" response
} |> Async.RunSynchronously
Run Code Online (Sandbox Code Playgroud)