从 Async F# 在主线程上执行代码

Execute Code on Main Thread from Async F#

我正在 F# 中实现以下 Swift 方法:

func downloadCachedImage(url : URL) {

if let cachedImage = imageCache.object(forKey: url.absoluteString as AnyObject) {
    self.image = cachedImage as! UIImage
}

URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in


    if (error != nil) {
        print(error)
        return
    }

    DispatchQueue.main.async {
        if let downloadedim = UIImage(data: data!) {
            imageCache.setObject(downloadedim, forKey: url.absoluteString as AnyObject)
            self.image = downloadedim
        }
    }
}).resume()

}

我是这样实现的:

    member this.downloadCachedImage(url : NSUrl) = 
        if imageCache.ObjectForKey(NSObject.FromObject(url.AbsoluteString)) <> null then 
            this.Image <- imageCache.ObjectForKey(NSObject.FromObject(url.AbsoluteString)) :?> UIImage
        else 
            let session : NSUrlSession = NSUrlSession.SharedSession
            let request : NSUrlRequest = NSUrlRequest.FromUrl(url)


            let downloadTask : NSUrlSessionDataTask = session.CreateDataTask(request, fun data response error -> 
                if error <> null then 
                    printfn "Error occurred"
                else 
                    let image = UIImage.LoadFromData(data)
                    imageCache.SetObjectforKey(image,new NSString(url.AbsoluteString))

                    this.Image <- image
            )
            downloadTask.Resume()

我唯一的问题是我需要代码:

this.Image <- image
在更新 UI 时,在主线程上

到 运行。在 Swift 中,这是通过块实现的:

DispatchQueue.main.async {...}

但是,我不知道如何在 F# 中执行此操作。

您可以试试这个返回主线程:

InvokeOnMainThread(fun _ -> ... ) 

但是我觉得当你从completionHandler获取数据的时候,它已经在主线程了。