Andries
Andries

Reputation: 1527

Is asynchronous in C# the same implementation as in F#?

Is the asynchronous implementation in C# 4.5 exactly the same as in F# 2 in the way threads are used?

Upvotes: 20

Views: 787

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243126

They are different. The main difference is that C# uses standard .NET Task<T> to represent asynchronous computations while F# uses its own type called Async<T>.

More specifically, the key differences are:

  • A C# async method creates a Task<T> that is immediately started (hot task model) while F# creates a computation that you have to start explicitly (generator model). This means that F# computations are easier to compose (you can write higher level abstractions).

  • In F# you also get better control over how is the computation started. You can start a computation using Async.Start to start it in the background or Async.StartImmediate to start it on the current thread.

  • F# asynchronous workflows support cancellation automatically, so you do not have to pass CancellationToken around.

  • Perhaps another consequence of the first point is that F# async workflows also support tail-recursion, so you can write recursive workflows (this would not work easily in C#, but C# does not use this programming style)

I wrote a more detailed article about this topic: Asynchronous C# and F# (II.): How do they differ?

Upvotes: 28

Related Questions