2

How do I create a TaskCompletionSource for a Task instead of a Task<TResult>?

3
  • @ReedCopsey: I rollbacked your edit because it changes the nature of the question in a non-intuitive way. If that's what the OP intended, they should edit it themself. Commented Jul 5, 2013 at 20:07
  • 1
    @Douglas My edit was just putting formatting in place - the original poster had Task<TResult>, but hadn't formatted it correctly. I did not change any content. Check the edit - all I did was add in the ``` characters appropriately. Commented Jul 5, 2013 at 20:08
  • @ReedCopsey: You're right; my apologies. Commented Jul 5, 2013 at 20:12

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.