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

C# 如何从异步方法返回字符串?,c#,async-await,C#,Async Await,我想从异步方法返回一个字符串值。我该怎么做?方法“getPlayerName”现在使用异步。但是此方法的使用者需要一个字符串值 public DataTable ToDataTable(List<AuctionInfo> data) { PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(AuctionInfo)); DataTable table = new Da

我想从异步方法返回一个字符串值。我该怎么做?方法“getPlayerName”现在使用异步。但是此方法的使用者需要一个字符串值

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;
}
公共数据表到数据表(列表数据)
{
PropertyDescriptorCollection properties=TypeDescriptor.GetProperties(typeof(AuctionInfo));
DataTable=新的DataTable();
//循环到所有列中
字符串propName=“PlayerName”;
table.Columns.Add(propName,propName.GetType());
foreach(属性中的PropertyDescriptor属性)
{
table.Columns.Add(prop.Name,Nullable.GetUnderlyingType(prop.PropertyType)??prop.PropertyType);
}
//todo添加列PlayerName
//循环进入所有拍卖/广告
foreach(数据中的AuctionInfo AuctionInfo)
{
DataRow行=table.NewRow();
行[“玩家名称”]=getPlayerName(拍卖信息);
//循环到所有列并设置值
foreach(属性中的PropertyDescriptor属性)
{
//列的设置值
行[prop.Name]=prop.GetValue(auctionInfo)??DBNull.Value;
}
//将行添加到数据表
table.Rows.Add(行);
}
返回表;
}
专用异步任务getPlayerName(AuctionInfo AuctionInfo)
{
var item=await client.GetItemAsync(auctionInfo);
string fullName=string.Format(“{0}{1}”,item.FirstName,item.LastName);
返回全名;
}

您可以使用
wait
从返回的
任务
中提取
字符串

这要求
ToDataTable
成为
async
方法,因此应将其重命名为
ToDataTableAsync
,并更改为返回
任务


然后
ToDataTable
的调用者必须同样地使用
Wait
并成为
async
方法。
async
的这种增长是完全自然的,应该受到欢迎。在我的示例中,我将其描述为“始终异步”。

您可以使用
wait
从返回的
任务中提取
字符串

这要求
ToDataTable
成为
async
方法,因此应将其重命名为
ToDataTableAsync
,并更改为返回
任务


然后
ToDataTable
的调用者必须同样地使用
Wait
并成为
async
方法。
async
的这种增长是完全自然的,应该受到欢迎。在我的示例中,我将其描述为“一路异步”。

就像您对
GetItemAsync()
所做的那样:在调用站点中
getPlayerName()
之前添加
wait
?就像您对
GetItemAsync()
所做的那样:在调用站点中
getPlayerName()
之前添加
wait
row["PlayerName"] = await getPlayerNameAsync(auctionInfo);