Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# 6 .NET tasks - how to use

Tags:

f#

F# 6 introduced support for .NET tasks.

This snippet is shared everywhere - but what's the right way to call and use the result of the task (to e.g. printf it)?

let readFilesTask (path1, path2) =
   task {
        let! bytes1 = File.ReadAllBytesAsync(path1)
        let! bytes2 = File.ReadAllBytesAsync(path2)
        return Array.append bytes1 bytes2
   }

One option that works is:

let result = readFilesTask ("filaA", "fileB")
printf $"%A{result.Result}"

But is this the intended way of use?

like image 871
Alexander Zeitler Avatar asked Oct 14 '25 15:10

Alexander Zeitler


1 Answers

There are a few ways to work with tasks. What is the "intended" way will depend on what you are trying to achieve.

Also note that for many applications, async is only marginally slower but much easier to work with because it is "cold".

You can consume a task in another task using let! and do!:

task {
  let! x = someOtherTask ()
  do! andAnotherTask ()
  return x
}

You can start a task and not wait on the result (fire and forget):

let foo () = 
  task {
    printfn "Done."
  }

foo () |> ignore // tasks are "hot" unlike asyncs

You can turn a task into an Async<'t> using Async.AwaitTask:

async {
  do! 
    task {
      printfn "Done."
    }
    |> Async.AwaitTask
}

You can block the current thread until a task is complete:

let foo () = 
  task {
    printfn "Done."
  }

let t = foo ()
t.Result

I expect that most real applications will have lots of do! and let! statements, but only a few .Result calls in order to avoid blocking.

like image 70
sdgfsdh Avatar answered Oct 18 '25 01:10

sdgfsdh