这个问题基于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,但在我对此进行实验时,它并非无错误)
答案 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)