Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Task<bool> instantly

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?

like image 383
Vitalii Vasylenko Avatar asked Nov 07 '13 20:11

Vitalii Vasylenko


People also ask

How do I return a Boolean in Task?

To return Boolean from Task Synchronously, we can use Task. FromResult<TResult>(TResult) Method. This method creates a Task result that's completed successfully with the specified result. The calling method uses an await operator to suspend the caller's completion till called async method has finished successfully.

How do I return a Task without await?

C# Language Async-Await Returning a Task without awaitThere is only one asynchronous call inside the method. The asynchronous call is at the end of the method. Catching/handling exception that may happen within the Task is not necessary.

How do I return a Task in 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.

Is an async method that returns Task a return keyword?

DoSomething()' is an async method that returns 'Task', a return keyword must not be followed by an object expression.


1 Answers

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); } 
like image 96
David L Avatar answered Sep 21 '22 17:09

David L