I'm using break(); on this example.
How to return from async Task method?
JeffinAtl
161
Reputation points
My method is async Task like following.
public async Task MyMethod()
{
string[] lists = GetCustomerLists();
foreach (string lst in lists)
{
// do somethong
// if meet some condition to return
????
}
}
What is the correct way to return from the method among the followings?
- break;
- return;
- await Task.CompletedTask;
Accepted answer
2 additional answers
Sort by: Most helpful
-
Bruce (SqlWork.com) 71,686 Reputation points
2022-05-02T16:38:46.42+00:00 just return or break if you want fall though to the end of the method.
because it is an async method, the compiler will convert the return/exit to a return task.
-
Karen Payne MVP 35,551 Reputation points
2022-05-02T17:29:13.04+00:00 Here is an abstract example where all Customers from a specific country are returned in a class named CustomerOperations.
This it's Entity Framework but that doesn't matter, the same applies for other read operations. Think of
context.Customers
asstring[] lists = GetCustomerLists();
public static async Task<List<Customers>> ByCountry(int countryIdentifier) { return await Task.Run(async () => { await using var context = new NorthwindContext(); return await context.Customers .Where(customer => customer.CountryIdentifier == countryIdentifier) .Select(customer => customer) .ToListAsync(); }); }
Usage
public static async Task Demo() { int identifier = 12; var customers = await CustomerOperations.ByCountry(identifier); }