【问题标题】:Async method doesn't return string as expected [duplicate]异步方法未按预期返回字符串[重复]
【发布时间】:2021-10-04 17:11:48
【问题描述】:

我很确定这已得到解答,但我无法在 SO 中找到它。我想从我的异步方法返回一个字符串,但它返回“System.Threading.Tasks.Task`1[System.String]”,而不是字符串值。

调用代码:

DBSql dBSqlSources = new DBSql(ModuleMain.CurrentDatabase.DBServer, ModuleMain.CurrentDatabase.DBDatabase);
string dataSources = dBSqlSources.GetDataSourceAsync().ToString();

我的方法:

public async Task<string> GetDataSourceAsync()
{
  SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
  string ServerName = string.Empty, InstanceName  =string.Empty;
  StringBuilder FullServerName = new StringBuilder(string.Empty);

  DataTable table = await Task.Run(() => instance.GetDataSources());
  foreach (DataRow row in table.Rows)
  {
    try
    {
      ServerName = row["ServerName"].ToString();
      InstanceName = row["InstanceName"].ToString();
      if (!string.IsNullOrEmpty(InstanceName))
      {
        FullServerName.Append(string.Concat(ServerName, @"\", InstanceName));
      }
    }
    catch (Exception ex)
    {
      ModuleMain._Log.AddError($"GetDataSources, {ex.Message}");
      return string.Empty;
    }
  }
  return FullServerName.ToString();
}

【问题讨论】:

标签: c# async-await


【解决方案1】:

您的代码的问题在于调用函数。它应该有一个await 关键字,即。

string dataSources =  await dBSqlSources.GetDataSourceAsync();

不需要结尾的ToString(),因为返回的类型是Task&lt;string&gt;,字符串会通过await关键字从Task中提取出来。

(您原始帖子下方的所有cmets都表示相同的观点)

【讨论】:

    【解决方案2】:

    async 关键字将方法转换为 async 方法,它允许您在其主体中使用 await 关键字。当应用 await 关键字时,它会暂停调用方法并将控制权交还给其调用者,直到等待的任务完成了。

    您需要等待异步方法才能获得结果。

    DBSql dBSqlSources = new DBSql(ModuleMain.CurrentDatabase.DBServer, 
    ModuleMain.CurrentDatabase.DBDatabase);
    
    var dataSources = await dBSqlSources.GetDataSourceAsync();
    

    【讨论】:

      【解决方案3】:

      由于它是一个异步方法,它不能将普通值作为“正常”(同步)方法返回:像使用它一样调用该方法将导致调用者线程继续执行下一条指令,而异步方法并行运行。

      我认为这个问题可以帮助你How to make an Asynchronous Method return a value?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-27
        • 1970-01-01
        • 2018-12-02
        • 2020-08-11
        相关资源
        最近更新 更多