Execute Code on Main Thread from Async F#

2019-05-29 00:23发布

问题:

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.