Execute Code on Main Thread from Async F#

廉价感情. 提交于 2019-12-22 12:18:41

问题


I am implementing the following Swift method in F#:

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()

}

I have implemented it in the following way:

    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()

My only problem is that I need the code:

this.Image <- image

to run on the main thread as it updates the UI. In Swift, this is achieved with the block:

DispatchQueue.main.async {...}

however, I have no idea how to do this in F#.


回答1:


You may try this to go back to main thread:

InvokeOnMainThread(fun _ -> ... ) 

But I think when you get data from the completionHandler, it has been on the main thread.



来源:https://stackoverflow.com/questions/48520528/execute-code-on-main-thread-from-async-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!