Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 902
Arne Claassen Avatar asked May 27 '11 21:05

Arne Claassen


People also ask

How do you return a value from a task?

You want to return a task result to the client. Set the task's Result property with your user defined result object. The task's Result property is serialized and returned back to the client.

What should I return from Task C#?

The recommended return type of an asynchronous method in C# is Task. You should return Task<T> if you would like to write an asynchronous method that returns a value. If you would like to write an event handler, you can return void instead. Until C# 7.0 an asynchronous method could return Task, Task<T>, or void.

What is Waithandle in C#?

WaitAny Method (System. Threading) Waits for any of the elements in the specified array to receive a signal.

What is the data type of the result property of the Task class?

The Task<T> class has a Result property of type T that contains whatever you pass back with return statements in the method. The caller generally retrieves what's stored in the Result property implicitly, through the use of await .


1 Answers

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);
like image 200
Arne Claassen Avatar answered Oct 09 '22 09:10

Arne Claassen