繁体   English   中英

在异步C#方法中从DynamoDB表返回字符串值

[英]Return a string value from a DynamoDB table in an async C# method

因为我刚接触C#,很难理解与此相关的其他问题和答案,所以我希望这不是此处提出的其他问题的完全重复,而我不能利用这些其他问题。

我在DynamoDB中有一个带有两列的表: referenceValue 我正在尝试使用reference作为分区键来获取“值”列的Value 到目前为止,这是我尝试过的:

public async void GetData(string reference)
{
    var data = await _client.GetItemAsync(
        "my-data",
        new Dictionary<string, AttributeValue>
        {
            {"reference", new AttributeValue {S = reference}}
        }
    );

    var item = data.Item.Values.First().S;

    System.Console.WriteLine(item);
}

我想返回为字符串的item变量,但是由于该方法是async我不允许这样做。 如何从该方法返回字符串?

当方法异步时,您应该返回Task 另外,通常应避免从异步方法返回void 相反,如果没有返回值,则返回Task 有一个完整的解释在这里

假设您的item类型为T ,那么通常您从async方法返回,例如:

public async Task<T> GetData(string reference)
{
    var data = await _client.GetItemAsync(
        "my-data",
        new Dictionary<string, AttributeValue>
        {
            {"reference", new AttributeValue {S = reference}}
        }
    );

    return data.Item.Values.First().S;
}

因此,如果您的item是字符串,则应为

public async Task<string> GetData(string reference)
{
    var data = await _client.GetItemAsync(
        "my-data",
        new Dictionary<string, AttributeValue>
        {
            {"reference", new AttributeValue {S = reference}}
        }
    );

    return data.Item.Values.First().S;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM