本文介绍了返回任务< bool>即刻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务列表,我想等待.我在等待

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()返回任务列表:

MyViewModel.GetListOfTasks() returns List of Task:

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

现在,我想返回虚拟任务,该任务将立即完成.但是,TaskEx.WhenAll会永远等待它:

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

我该如何退回立即完成的Task?

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

推荐答案

在.NET 4.5中,您可以使用FromResult立即返回任务结果.

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

对于Windows Phone 8.1及更高版本, API已被合并以与其他平台保持一致:

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

这篇关于返回任务&lt; bool&gt;即刻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:42