Return Task<bool> instantly

84,274

Solution 1

in .NET 4.5 you can use FromResult to immediately return a result for your task.

public Task<bool> MyTask()
{
    return TaskEx.FromResult(false);
}

http://msdn.microsoft.com/en-us/library/hh228607%28v=vs.110%29.aspx


For Windows Phone 8.1 and higher, the API has been merged to be consistent with other platforms:

public Task<bool> MyTask()
{
    return Task.FromResult(false);
}

Solution 2

Prior to .NET 4.5, you can use TaskCompletionSource<TResult> to simulate the FromResult method.

public static Task<TResult> FromResult<TResult>(TResult result)
{
    var completionSource = new TaskCompletionSource<TResult>();
    completionSource.SetResult(result);
    return completionSource.Task;
}
Share:
84,274
Vitalii Vasylenko
Author by

Vitalii Vasylenko

Developer from Ukraine

Updated on July 09, 2022

Comments

  • Vitalii Vasylenko
    Vitalii Vasylenko almost 2 years

    I have a list of tasks, which i'd like to wait for. I'm waiting like

        await TaskEx.WhenAll(MyViewModel.GetListOfTasks().ToArray());
    

    MyViewModel.GetListOfTasks() returns List of Task:

        var tasksList = new List<Task>();
        foreach (var item in Items)
        {                
            tasksList.Add(item.MyTask());
        }
    

    Now, i'd like to return dummy task, which would be done immediately. However, TaskEx.WhenAll would wait it forever:

        public Task<bool> MyTask()
        {
            return new Task<bool>(() => false);
        }
    

    How can i return Task, which would be finished instantly?

  • Vitalii Vasylenko
    Vitalii Vasylenko over 10 years
    But why would i want to simulate it? Thanks anyway.
  • Sam Harwell
    Sam Harwell over 10 years
    @VitaliiVasylenko Because prior to .NET 4.5, there is no FromResult method.
  • Vitalii Vasylenko
    Vitalii Vasylenko over 10 years
  • Scott Chamberlain
    Scott Chamberlain over 10 years
    @VitaliiVasylenko You are looking at 4.5, go up a level and change the .net version to 4.0 and you will see FromResult is not an available method.
  • Vitalii Vasylenko
    Vitalii Vasylenko over 10 years
    @ScottChamberlain But we are talking about 4.5?
  • Vitalii Vasylenko
    Vitalii Vasylenko over 10 years
    @280Z28 Well, anyway, thanks for your answer - its always good to keep analogues in mind, and to know what's inside.
  • Taiseer Joudeh
    Taiseer Joudeh over 9 years
    @SamHarwell Thank you, this was very useful.
  • Bionic
    Bionic about 7 years
    Since the final release of the Framework its: return Task.FromResult(false);
  • David L
    David L about 7 years
    @uli78 this question was specifically for windows phone 7, but great point! I've updated my answer, thank you!