5

I want to implement function that return list of child items from database asynchronously. So I write a function:

    public async Task<IEnumerable<object>> GetFiles(int parentId)
    {
        var data = from file in DB.Files
                   where file.ParentId == parentId
                   select new { name = file.Name, id = file.Id };
        return data;
    }

However I can see a warning: Async method lasks 'await' operators and will run synchronously. How to rewrite this function into asynchronous?

2
  • 1
    Just a side note to say that you're approach the problem from the wrong direction. You should never "make a method async" and then figure out how to do it. Instead, consider all the I/O of your app, make them use await, and then let it grow from there. In other words, use something like ToListAsync before you mark the method async. Commented Jun 3, 2016 at 16:28
  • Since the only purpose of my method is to get some data from database it should be async from the start Commented Jun 5, 2016 at 6:31

3 Answers 3

8

Your can use ToListAsync().

https://msdn.microsoft.com/en-us/library/dn220258(v=vs.113).aspx

var data = await DB.Files
    .Where(file => file.ParentId == parentId)
    .Select
        (
            new 
            { 
                name = file.Name,
                id = file.Id 
            }
        ).ToListAsync();
return data;

Alternatively:

var data = from file in DB.Files
           where file.ParentId == parentId
           select new { name = file.Name, id = file.Id };
return await data.ToListAsync();

Be aware that this will query the data. Also, you may reconsider your method name. When a method is async the naming convention suggest that you append "Async" to your method name.

By convention, you append "Async" to the names of methods that have an Async or async modifier.

Sign up to request clarification or add additional context in comments.

Comments

6

ToListAsync() method is not working with enumarable anymore. You can use FromResult method like below :

var data = from file in DB.Files
           where file.ParentId == parentId
           select new { name = file.Name, id = file.Id };
    return await Task.FromResult(data);

1 Comment

Your answer makes no sense, since as per your linked document about ToListAsync it returns a Task<List> and List-class implements IEnumerable. So yes the return value of ToListAsync is enumerable.
-2

Alternatively you could use, TaskCompletionSource -

public static async Task<string> ReturnAsync()
{
    var tsc = new TaskCompletionSource<string>();
    tsc.SetResult("hello world");
    return await tsc.Task;
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.