从异步F#执行主线程上的代码

时间:2018-01-30 11:38:40

标签: swift multithreading f# xamarin.ios nsurlsession

我在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#中这样做。

1 个答案:

答案 0 :(得分:1)

你可以尝试这回到主线程:

InvokeOnMainThread(fun _ -> ... ) 

但我认为当你从completionHandler获取数据时,它一直在主线上。