-1

I'm quite sure this was answered but I can't find it into SO. I want to return a string from my async method, but it returns "System.Threading.Tasks.Task`1[System.String]", not the string value.

Calling code:

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

My method:

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();
}
GSerg
  • 76,472
  • 17
  • 159
  • 346

3 Answers3

1

The problem with your code is the calling function. It should have an await keyword, ie.

string dataSources =  await dBSqlSources.GetDataSourceAsync();

The trailing ToString() is not needed, because the returned type is Task<string>, and the string will be extracted from the Task by the await keyword.

(All the comments below your original post make the same point)

Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79
0

The async keyword turns a method into an async method, which allows you to use the await keyword in its body.. when the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.

You need to await the async method to get the results.

DBSql dBSqlSources = new DBSql(ModuleMain.CurrentDatabase.DBServer, 
ModuleMain.CurrentDatabase.DBDatabase);

var dataSources = await dBSqlSources.GetDataSourceAsync();
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
-1

As it's an async method it can't return a plain value as a 'normal' (sync) method: calling the method like you are using it will result in the caller thread to proceed to the next instructions, while the async method runs in parallel.

I think this question could help you How to make an Asynchronous Method return a value?

Igor
  • 157
  • 7