Ola
Ola

Reputation: 1208

How to return a string from an async method?

I would like to return a string value from a async method. How can I do this? The method "getPlayerName" is using now async. But the consumer of this method is expecting a string value.

public DataTable ToDataTable(List<AuctionInfo> data)
{
    PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(AuctionInfo));
    DataTable table = new DataTable();

    // loop into all columns
    string propName = "PlayerName";
    table.Columns.Add(propName, propName.GetType());
    foreach (PropertyDescriptor prop in properties)
    {
        table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
    }
    // todo add column PlayerName


    // loop into all auctions/advertenties
    foreach (AuctionInfo auctionInfo in data)
    {
        DataRow row = table.NewRow();

        row["PlayerName"] = getPlayerName(auctionInfo);
        // loop into all columns and set value
        foreach (PropertyDescriptor prop in properties)
        {
            // set value of column
            row[prop.Name] = prop.GetValue(auctionInfo) ?? DBNull.Value;
        }

        // add row to datatable
        table.Rows.Add(row);
    }
    return table;
}

private async Task<string> getPlayerName(AuctionInfo auctionInfo)
{
    var item = await client.GetItemAsync(auctionInfo);
    string fullName = string.Format("{0} {1}", item.FirstName, item.LastName);
    return fullName;
}

Upvotes: 0

Views: 884

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456507

You use await to extract the string from the returned Task<string>:

row["PlayerName"] = await getPlayerNameAsync(auctionInfo);

This requires ToDataTable to become an async method, so it should be renamed ToDataTableAsync and changed to return a Task<DataTable>.

Then the callers of ToDataTable must similarly use await and become async methods. This growth of async is perfectly natural and should be embraced. In my async best practices article, I describe this as "async all the way".

Upvotes: 4

Related Questions