Thomas
Thomas

Reputation: 12127

Can someone clarify the use cases betwen Task and Async in F# 6?

I have read this article: https://www.compositional-it.com/news-blog/task-vs-async/ that covers the updates in F# 6.

There is a chapter about the introduction of the task expression and its similarity and differences with async.

My understanding is that the task is a block in which we can do async calls, but it is executed in the regular flow, whereas the async block is the one we know, that creates expressions that will be executed later, on demand.

I use async quite extensively since I'm working with an app doing a lot of data streaming and database writing, so everything is pretty much async.

The only use I can see with the task expression is to interface with async api where I want the async block to run right now. Essentially, replacing:

async {
    do! callMyAsyncOnlyApi ()
} |> Async.RunSynchronously

with

task {
    do! callMyAsyncOnlyApi ()
}

which would run instantl and release the cpu while waiting.

I must be missing something :D

Upvotes: 1

Views: 207

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243126

The article provides an excellent summary in the conclusion section:

Personally, I reach for async {} by default unless I am dealing with external Task based libraries or I face a specific performance issue (which hasn't happened yet!). I find it fits the functional mindset better and is easier to use.

The reality is however that a great deal of libraries have been written with Task in mind, and it is fantastic that F# now has first class, out of the box support for the pattern.

I do not think there is much to add:

  • F# always had async and async is a reasonable default
  • There are a number of advantages of async - it supports cancellation and uses the "generator" model which is more composable (and more F# friendly)
  • .NET uses Task<T> more prominently, so if you are interfacing with a lot of .NET libraries (as your question suggests), then you may choose task
  • task can be more efficient if you have CPU-bound and not IO-bound code - so in some cases, you may choose that for performance reasons

Upvotes: 4

Related Questions