我一直在Playground中的中级Swift WWDC会话中关注弱引用示例.我稍微修改了代码如下:
class Apartment {
let address: Int
init(address: Int) {
self.address = address
}
weak var tenant: Person?
}
class Person {
let name: String
init(name: String){
self.name = name
}
weak var home: Apartment?
func moveIn(apt: Apartment) {
self.home = apt
apt.tenant = self
}
}
var renters = ["John Appleseed": Person(name: "John Appleseed")]
var apts = [16: Apartment(address: 16)]
renters["John Appleseed"]!.moveIn(apts[16]!)
renters["John Appleseed"] = nil // memory should be released here
// then apts[16].tenant should …Run Code Online (Sandbox Code Playgroud) 我正在尝试在Async.AwaitObservable开始使用的异步工作流程中使用Fsharpx Async.StartWithContinuations.出于某种原因,如果用于启动此工作流的取消令牌在等待可观察时被取消(但在工作流的其他部分期间不被取消),则永远不会调用取消继续.但是,如果我把它放在一个中use! __ = Async.OnCancel (interruption),那么就会调用中断函数.有人可以澄清为什么会发生这种情况,最好的方法是做什么,并确保其中一个延续函数始终被调用?
open System
open System.Reactive.Linq
open FSharp.Control.Observable
open System.Threading
[<EntryPoint>]
let main _ =
let cancellationCapability = new CancellationTokenSource()
let tick = Observable.Interval(TimeSpan.FromSeconds 1.0)
let test = async {
let! __ = Async.AwaitObservable tick
printfn "Got a thing." }
Async.StartWithContinuations(test,
(fun () -> printfn "Finished"),
(fun exn -> printfn "Error!"),
(fun exn -> printfn "Canceled!"),
cancellationCapability.Token)
Thread.Sleep 100
printfn "Cancelling..."
cancellationCapability.Cancel()
Console.ReadLine() |> ignore
0 // return an integer exit …Run Code Online (Sandbox Code Playgroud)