Taskcompletionsource<Tresult> without a type parameter

Asked

Viewed 59 times

2

The class TaskCompletionSource<TResult> needs a type TResult. That way, when I need to use this class without having a return type (void), I have to do something like:

var tcs = new TaskCompletionSource<object>();
// ...
tcs.TrySetResult(null);

I don’t know if this is the best way to do when the return of a function is only one Task, of no kind. It seems to me.

There is no TaskCompletionSource without the type parameter? There is another output?

2 answers

1

IS by-design. I saw in the Soen that there is a microsoft document, written by Stephen Toub, "The Task-based Asynchronous Pattern", which says:

There is no non-generic Counterpart to TaskCompletionSource<TResult>. However, Task<TResult> derives from Task, and Thus the Generic TaskCompletionSource<TResult> can be used for I/O-bound methods that Simply Return a Task by Utilizing a source with a dummy TResult (bool is a good default Choice, and if a Developer is concerned about a Consumer of the Task downcasting it to Task<TResult>, a private TResult type may be used)

Ali says to use a boolean on the guy, but Stephen Cleary doesn’t recommend it, since object with the value null takes away meaning, and a value true or false leaves some meaning in the value returned. Anyway, matter of semantics.

1


There is no better form today. There is no TaskCompletionSource without a result to be defined.

What may be a gain, but I have doubts is to return a type by value and not object to avoid allocation in heap. but it will be a very small gain and I do not know if it will generate any consequences in other parts.

If you want to learn all about asynchrony and . NET tasks this is the guy to follow.

  • I already knew Stephen by Soen, but I didn’t know that it was a reference of asynchrony in .NET. I will read some of his things.

  • 1

    He’s an expert. Of course there’s Jon Skeet and others. There’s people from the team. NET as Jared Parsons, had the compiler’s Eric Lippert who talks a lot about the more conceptual part and how the compiler deals with it. Joe Duffy was the guy who created all the homework.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.