Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to return a Task<List<string>> via c#?

I'm currently making my first steps with VS2012 and .NET 4.5 with async and await.

for this I'm implementing a method with the following signature:

public Task<List<string>> foo() {...}

I know how to return a List but I dont know how to get this list into a Task<>. How to do it?

EDIT: here is the complete example, I need to knwo what I need to change to make the return statement possible

public async Task<List<string>> foo()
{
    List<string> myList = new List<string>;
        {...}
    return mylist;
}
like image 727
gurehbgui Avatar asked Dec 27 '22 12:12

gurehbgui


1 Answers

If your method is actually asynchronous, you can simply add the async keyword, and the compiler will generate a Task for you.

You can also write asynchronous code by hand, using ContinueWith() on an existing task or using the static methods on the Task class to create new tasks.

If your method is not asynchronous, there's no point; you should return a List<string> directly.
If, for some reason, you need to return a pre-completed Task<T> from a synchronous method (if you're implementing an interface), you can call Task.FromResult.

like image 116
SLaks Avatar answered Jan 04 '23 22:01

SLaks