I am coding a long running operation in FSharp's taks CE as follows
let longRunningTask = Task.Run(...)
// Now let's do the rest of the multi-tasking program
task {
DO SOMETHING
let! result = longRunningTask
DO SOMETHING ELSE
}
The problem is DO SOMETHING ELSE appears to be running on an arbitrary thread (as observed also by printing the current thread id), whereas I absolutely need it to run on the same thread as DO SOMETHING, as I don't want any other form of concurrency except for the longRunningTask.
I've tried in many ways to set the current synchronization context, creating first a unique value of that type, but that doesn't seem to affect the result.
It might be an overkill, but SynchronizationContext may help you. It's used to dispatch delegates to some threads. There's a lot of explanations on how it's working (search for
ConfigureAwait(false)), so I'll focus on implementationNotes on methods:
Post: Method which is executed on async path. This method is called from infrastructure ofTaskwhen C#awaitor F#let!do!completes asynchronously. Callback is queued to be completed sometime.Send: Method which is executed on sync path. It's expected thatcallbackwill be executed before this method returns. For example when someone calls aCancellationTokenSource.Cancelor WPF'sDispatcher.Invokeor WinFormsControl.InvokeDoWork: Method which blocks current thread to execute all pending callback, because we can't just interrupt thread to perform some task, it must be waiting for it.Usage: