Reputation: 70307
How do I create a TaskCompletionSource
for a Task
instead of a Task<TResult>
?
Upvotes: 2
Views: 464
Reputation: 564363
There is no non-generic version. However, Task<T>
derives from Task
, so you can just use TaskCompletionSource<bool>
and return the task.
Task SomeMethodAsync()
{
var tcs = new TaskCompletionSource<bool>();
// Implement method as needed
return tcs.Task; // Return the Task<bool> as a Task
}
Note that I'm using bool
just because it's a small value type, and the result will get "thrown away". Another option here is to make your own custom type and return that, ie:
private struct EmptyType {}
Task SomeMethodAsync()
{
var tcs = new TaskCompletionSource<EmptyType>();
// Implement method as needed
// Use tcs.SetResult(default(EmptyType)) or similar
return tcs.Task; // Return the Task<bool> as a Task
}
The main advantage here is the type is the smallest possible (least waste), and a type that doesn't suggest there is a "value" contained within the result (if the consumer does use reflection, etc).
Upvotes: 4