I have not tested this, but I think the easiest way to achieve what you want is to combine the SynchronizationContext.Send
method (mentioned in the comments) with the Async.StartImmediate
operation. The former lets you start some work synchronously in the synchronization context. The latter lets you start an async workflow in the current context.
If you combine the two, you can define a helper that starts a function in a given synchronization context and, in this function, immediately starts an async workflow:
let startInContext (sync:SynchronizationContext) work =
SynchronizationContext.Current.Send((fun _ ->
Async.StartImmediate(work)), null)
For example:
async {
printfn "Running on the given sync context"
do! Async.Sleep(1000)
printfn "Should be back on the original sync context" }
|> startInContext SynchronizationContext.Current
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…