0

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;
}
1
  • As you did for GetItemAsync(): adding await before getPlayerName() in the calling site? Commented Oct 28, 2014 at 16:48

1 Answer 1

4

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.