Home > Net >  .NET - How can I convert a Task<> to Task (with no type parameter)?
.NET - How can I convert a Task<> to Task (with no type parameter)?

Time:11-19

Task<T> is a separate class from Task (no type parameter), and there are some functions that only accept untyped Task as a parameter. How can I convert a Task<T> to a Task (with no type parameter)?

Examples in F#, but same principle applies to C#.

This F# function:

let getTask = task {
    return ()
}

creates a Task<unit>.

CodePudding user response:

You can just cast:

let t = getTask() :> Task

-Also, FSharp.Control.FusionTasks has a bunch of helper functions. In this case, it’d be Task.ignore.- edit: it’s a different lib, lemmecheck on that, brb.

CodePudding user response:

One way is to use the ContinueWith() method of Task<T>.

C# example: var untypedTask = task.ContinueWith(t => { });

F# example: let untypedTask = task.ContinueWith(Action<Task<unit>>(ignore))

  • Related