【发布时间】: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();
}
【问题讨论】:
-
这能回答你的问题吗? Async Await code. Why it is not working?
-
这能回答你的问题吗? Converting async Task Response to String
-
@GSerg 当然可以,非常感谢
标签: c# async-await