【问题标题】:F# async lambda declarationF# 异步 lambda 声明
【发布时间】:2014-07-19 06:37:33
【问题描述】:

在 C# Xamarin iOS 中我可以这样做:

InvokeOnMainThread( () => { //do stuff here});

InvokeOnMainThread 的参数是 NSAction

在 F# 中我必须这样做

InvokeOnMainThread (new NSAction(fun _ -> //do stuff here))

但在 C# 中我也可以这样做

InvokeOnMainThread (async () => { //do stuff here});

我将如何在 F# 中做同样的事情?


另外,就我而言,在 C# 中我这样做:

InvokeOnMainThread(async() => { await Task.Delay(1100); });

我如何在 F# 中表达相同的东西?

【问题讨论】:

  • InvokeOnMainThread (async () => { /* do stuff here */ }) 如果我正确阅读了the docs,这将从 lambda 创建一个async void 方法。这很可能不是您想要的(尝试在延迟后抛出异常)。

标签: ios asynchronous f# xamarin


【解决方案1】:

我没有安装 Xamarin 来实际尝试这个,但我认为以下应该可以解决问题:

InvokeOnMainThread(NSAction(fun _ -> 
   async { do! Async.Sleep(1000)
           (* some more stuff *) }
   |> Async.StartImmediate
))

我有点疑惑为什么你需要指定 NSAction 委托类型,但我想它可能存在一些重载问题,所以也许它实际上是需要的。

上面的例子创建了一个普通的 lambda 函数,它在函数体内创建了一个异步块,然后立即在当前线程上启动它。这是一个合理的选择,因为您从睡眠开始 - 但如果您正在做一些 CPU 密集型工作,最好使用 Async.Start 在后台启动异步。

【讨论】:

  • 谢谢!实际上,在问上一个问题之前,我可能应该在 github 上阅读更多示例。而不是声明新的 NSAction 并使用 fun _ -> 你可以说 InvokeOnMainThread(fun() -> ... ) 也许只是一个学习过程!
猜你喜欢
  • 2023-03-07
  • 2020-11-25
  • 1970-01-01
  • 2019-03-25
  • 2018-10-03
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
  • 2021-08-31
相关资源
最近更新 更多