I want to use computation expressions inside the implementation of an F# class intended for C# consumption. The interop class itself is a singleton (one instance wired up in container) and is used across threads (web requests).
The builder itself consists only of methods and has no backing fields or state.
Given that the following is customary in F#:
module A =
let private build = new SomeBuilder()
Does this mean that multiple expressions associated with one builder can be evaluated concurrently with no problems?
Under the hood, builder doesn't "work" at all. The compiler simply converts the computation expression to a series of method calls on the builder, and then compiles that.
Therefore, thread-safety of the builder is wholly dependent on thread-safety of its methods - i.e. the methods that you write.
For example, the following code:
myBuilder {
let! x = f()
let! y = g(x)
return x + y
}
Would be converted into the following:
myBuilder.Bind( f(), fun x ->
myBuilder.Bind( g(x), fun y ->
myBuilder.Return( x + y ) ) )
(NOTE: the above code may not be exact, but it conveys the gist)
A pure, stateless builder is safe for concurrent usage.
Computation expressions are basically syntax sugar. There's no effective difference between using a builder's computation expressions or calling its methods directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With