TaskCompletionSourceTResult without a type parameter

2

The TaskCompletionSource<TResult> class needs a TResult type. 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 do not know if this is the best way to do when the return of a function is only a Task , with no type at all. It seems to me gambiarra.

Is there no TaskCompletionSource without the type parameter? Is there another way out?

    
asked by anonymous 08.11.2017 / 03:20

2 answers

1

I'm no expert on this, but I do not think it has a better shape these days. There is no TaskCompletionSource without a result to be defined.

What might be a gain, but I have questions 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 elsewhere.

If you want to learn everything about asynchronism and .NET tasks this is the guy to follow .

    
08.11.2017 / 11:58
1

It's by-design . I saw in the SOen that there is a #, written by Stephen Toub, "The Task-based Asynchronous pattern," which reads:

  

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 to 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> , private TResult type may be used)

There it says to use a boolean in the type, but Stephen Cleary does not recommend, since% w / o% with value% w /% takes the meaning, and a% w / o% w /% w / w% leaves some meaning in value returned. Anyway, matter of semantics.

    
19.11.2017 / 13:26