Search code examples
c#task-parallel-libraryasync-awaitasync-ctp

Is there a way to use Task<T> as a waithandle for a future value T?


I'd like to use Task return from a method to return a the value when it becomes available at later time, so that the caller can either block using Wait or attach a continuation or even await it. The best I can think of is this:

 public class Future<T> {
    private ManualResetEvent mre = new ManualResetEvent();
    private T value;
    public async Task<T> GetTask() {
        mre.WaitOne();
        return value;
    }
    public void Return(T value) {
        this.value = value;
        mre.Set();
    }
}

Main problem with that is that mre.WaitOne() is blocking, so i assume that every call to GetTask() will schedule a new thread to block. Is there a way to await a WaitHandle in an async manner or is there already a helper for building the equivalent functionality?

Edit: Ok, is TaskCompletionSource what i'm looking for and i'm just making life hard on myself?


Solution

  • Well, I guess I should have dug around a bit more before posting. TaskCompletionSource is exactly what I was looking for

    var tcs = new TaskCompletionSource<int>();
    bool completed = false;
    var tc = tcs.Task.ContinueWith(t => completed = t.IsCompleted);
    tcs.SetResult(1);
    tc.Wait();
    Assert.IsTrue(completed);