Overlord Zurg
Overlord Zurg

Reputation: 3794

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

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>.

Upvotes: 1

Views: 394

Answers (2)

Abel
Abel

Reputation: 57159

You can just cast:

let t = getTask() :> Task

Conversely, in case you'd need a Task<unit> from any Task or Task<'T>, F#+ Task.ignore function is helpful, or you could write your own:

let asUnitTask t = task { let! _ = t; return () }

Upvotes: 3

Overlord Zurg
Overlord Zurg

Reputation: 3794

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))

Upvotes: -2

Related Questions