Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with ValueTask<T> in F#?

Tags:

So apparently .NET's brand new ValueTask<T> is the leaner version of Task<T>. That's cool, but if before I had to use Async.AwaitTask to integrate my F# Async workflows with Task, what should I do with ValueTask now?

like image 622
knocte Avatar asked Sep 18 '18 07:09

knocte


People also ask

When should I use ValueTask?

Here is the rule of the thumb. Use Task when you have a piece of code that will always be asynchronous, i.e., when the operation will not immediately complete. Take advantage of ValueTask when the result of an asynchronous operation is already available or when you already have a cached result.

How do I return a task in C#?

You use the void return type in asynchronous event handlers, which require a void return type. For methods other than event handlers that don't return a value, you should return a Task instead, because an async method that returns void can't be awaited.

What is the difference between task and value task?

As you know Task is a reference type and it is allocated on the heap but on the contrary, ValueTask is a value type and it is initialized on the stack so it would make a better performance in this scenario.


2 Answers

Before Async.AwaitValueTask is implemented (thanks Aaron), one can use ValueTask's AsTask method, and use Async.AwaitTask for now, as the simplest solution.

like image 67
knocte Avatar answered Oct 06 '22 16:10

knocte


My OSS project "FusionTasks" can handle naturally and implicitly interprets both Task and ValueTask same as F# Async type on F# async workflow:

let asyncTest = async {
  use ms = new MemoryStream()

  // FusionTasks directly interpreted Task class in F# async-workflow block.
  do! ms.WriteAsync(data, 0, data.Length)
  do ms.Position <- 0L

  // FusionTasks directly interpreted Task<T> class in F# async-workflow block.
  let! length = ms.ReadAsync(data2, 0, data2.Length)
  do length |> should equal data2.Length
}
like image 36
Kouji Matsui Avatar answered Oct 06 '22 16:10

Kouji Matsui