Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

asynchronous - F#: Synchronously start Async within a SynchronizationContext

Async.SwitchSynchronizationContext allows an Async action to switch to running within a given SynchronizationContext. I would like to synchronously begin an Async computation within a SynchronizationContext, rather than switching inside the Async.

This would ensure that Async actions are run in the desired order, and that they are not run concurrently.

Is this possible? The documentation for Async.SwitchSynchronizationContext mentions using SynchronizationContext.Post, but no such functionality is exposed for Async.

question from:https://stackoverflow.com/questions/65890049/f-synchronously-start-async-within-a-synchronizationcontext

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...