Sam
Sam

Reputation: 30344

Async method that does not make async calls

I need to create a method that will connect to my Azure SQL database and read some data. All the methods that call this method are async methods but I don't think I can make the ReadStateProvinceListAsync an async one.

What's the right approach in these situations? Just ignore the "warning" from the compiler that I have an async method that does not use the await keyword or make the ReadStateProvinceListAsync method a regular synchronous method in which case the GetStateProvinceListAsync method will give me the same warning.

I want to do it right -- by the book. That's why I want to learn the right approach.

public static async Task<List<StateProvince>> GetStateProvinceListAsync(string countryId)
{
   // Check to see if I already have this data cached
   if(gotData)
   {
      // Life is good! Get data from cache.
   }
   else
   {
      // Don't have the data cached. Call the DB read method
      statesList = await ReadStateProvinceListAsync(countryId)
   }
}

private static async Task<List<StateProvince>> ReadStateProvinceListAsync(string countryId)
{
   // Call Azure SQL Database to read data. No async code here!
}

Upvotes: 0

Views: 183

Answers (1)

i3arnon
i3arnon

Reputation: 116636

There's absolutely no value in marking a synchronous method with the async keyword. If your method doesn't make any asynchronous calls make it synchronous:

public static List<StateProvince> GetStateProvinceListAsync(string countryId)
{
   // Check to see if I already have this data cached
   if(gotData)
   {
      // Life is good! Get data from cache.
   }
   else
   {
      // Don't have the data cached. Call the DB read method
      statesList = ReadStateProvinceList(countryId)
   }
}

private static List<StateProvince> ReadStateProvinceList(string countryId)
{
   // Call Azure SQL Database to read data. No async code here!
}

If for some reason you must return a task (e.g. it's an interface or abstract implementation) use Task.FromResult to return a Task synchronously:

private static Task<List<StateProvince>> ReadStateProvinceListAsync(string countryId)
{
    return Task.FromResult(ReadStateProvinceList());
}

Upvotes: 3

Related Questions