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?
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With