Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using the same instance of a builder class concurrently cause any side effects?

Tags:

f#

c#-to-f#

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?

like image 889
moarboilerplate Avatar asked Feb 05 '16 15:02

moarboilerplate


2 Answers

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)

like image 188
Fyodor Soikin Avatar answered Nov 09 '22 00:11

Fyodor Soikin


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.

like image 5
Vandroiy Avatar answered Nov 08 '22 23:11

Vandroiy