如何从异步方法返回字符串

本文关键字:返回 字符串 异步方法 | 更新日期: 2023-09-27 18:28:05

我想从异步方法返回一个字符串值。我该怎么做?方法"getPlayerName"现在正在使用async。但是这个方法的使用者期望得到一个字符串值。

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;
}

如何从异步方法返回字符串

使用await从返回的Task<string>:中提取string

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

这需要ToDataTable成为async方法,因此应将其重命名为ToDataTableAsync并更改为返回Task<DataTable>

那么ToDataTable的调用方必须类似地使用await并成为async方法。async的这种生长是完全自然的,应该被接受。在我的async最佳实践文章中,我将其描述为"一路异步"。