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?
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.
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.
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.
Before Async.AwaitValueTask
is implemented (thanks Aaron), one can use ValueTask's AsTask method, and use Async.AwaitTask
for now, as the simplest solution.
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
}
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