Return Task<bool> instantly

C#MultithreadingWindows Phone-7Task Parallel-Library

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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 - C#

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;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVitalii VasylenkoView Question on Stackoverflow
Solution 1 - C#David LView Answer on Stackoverflow
Solution 2 - C#Sam HarwellView Answer on Stackoverflow