How to return from async Task method?

JeffinAtl 161 Reputation points
2022-05-02T15:09:42.517+00:00

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?

  1. break;
  2. return;
  3. await Task.CompletedTask;
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,239 questions
{count} votes

Accepted answer
  1. Jamie Hayashi 121 Reputation points
    2022-05-02T22:50:54.13+00:00

    I'm using break(); on this example.


2 additional answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,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.

    0 comments No comments

  2. Karen Payne MVP 35,036 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 as string[] 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);
    }
    
    0 comments No comments