从异步F#在主线程上执行代码 [英] Execute Code on Main Thread from Async F#

查看:104
本文介绍了从异步F#在主线程上执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在更新UI时在主线程上运行.在Swift中,这是通过以下代码块实现的:

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

DispatchQueue.main.async {...}

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

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

推荐答案

您可以尝试使用此方法返回主线程:

You may try this to go back to main thread:

InvokeOnMainThread(fun _ -> ... ) 

但是我认为当您从completionHandler获取数据时,它已经在主线程上.

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

这篇关于从异步F#在主线程上执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆