正确的方法如何使用响应式UI在异步可取消工作流中准备数据

时间:2012-03-08 10:04:12

标签: user-interface asynchronous f# mailboxprocessor

这个问题基于Async.TryCancelled doesn't work with Async.RunSynchronously看起来很复杂,所以我会剪掉一个我试图解决的简单部分。

假设我有这个功能:

let prepareModel () = 
    async {
        // this might take a lot of time (1-50seconds)
        let! a = ...
        let! b = ...
        let! res = combine a b
        return res
    }
 let updateUI model =
    runOnUIThread model

prepareModel准备应向用户显示的数据。 updateUI刷新UI(删除旧控件并根据新数据创建新的ctl)。

问题:我应该如何调用这两个函数,以便prepareModel可以随时取消?

流程是

  • 用户点击刷新
    • prepareModel(1)启动并异步运行,因此用户界面响应迅速,用户可以使用该应用程序
  • 用户更改数据并再次点击刷新
    • prepareModel(1)from取消并且 新的prepareModel(2)已启动
  • 用户更改数据并再次点击刷新
    • prepareModel(2)被取消 新的prepareModel(3)已启动
    • ..
    • prepareModel(n)完成了
    • updateUI在UI线程上运行,重新绘制UI

(我的第一个解决方案基于MailboxProcessor,确保只执行一个prepareModel,请参阅Async.TryCancelled doesn't work with Async.RunSynchronously,但在我对此进行实验时,它并非无错误)

1 个答案:

答案 0 :(得分:5)

一种可能的方法是使用Async.Start在后​​台异步启动工作流(然后它应该是可取消的)。要在最后重绘UI,可以使用Async.SwitchToContext确保工作流的最后部分在UI上执行。这是一幅草图:

// Capture current synchronization context of the UI
// (this should run on the UI thread, i.e. when starting)
let syncContext = System.Threading.SynchronizationContext.Current

// Cancellation token source that is used for cancelling the
// currently running workflow (this can be mutable)
let cts = ref (new CancellationTokenSource())

// Workflow that does some calculations and then updates gui
let updateModel () =   
    async {  
        // this might take a lot of time (1-50seconds)  
        let! a = ...  
        let! b = ...  
        let! res = combine a b 

        // switch to the GUI thread and update UI
        do! Async.SwitchToContext(syncContext)
        updateUserInterface res
    }  

// This would be called in the click handler - cancel the previous
// computation, creat new cancellation token & start the new one
cts.Cancel()
cts := new CancellationTokenSource()
Async.Start(updateModel(), cts.Token)