不进行异步调用的异步方法

时间:2014-12-06 23:29:31

标签: c# .net asp.net-mvc asynchronous async-await

我需要创建一个连接到我的Azure SQL数据库并读取一些数据的方法。调用此方法的所有方法都是异步方法,但我不认为我可以使ReadStateProvinceListAsync成为async

在这些情况下,正确的方法是什么?只需忽略"警告"从编译器我有async方法不使用await关键字使ReadStateProvinceListAsync方法成为常规同步方法,在这种情况下GetStateProvinceListAsync 1}}方法会给我同样的警告。

我想通过这本书做得对。这就是我想学习正确方法的原因。

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!
}

1 个答案:

答案 0 :(得分:3)

使用async关键字标记同步方法绝对没有价值。如果您的方法没有进行任何异步调用,则使其同步:

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!
}

如果由于某种原因你必须返回任务(例如,它是一个接口或抽象实现),请使用Task.FromResult同步返回Task

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