简体   繁体   中英

How can I return an integer with async method in C#?

I need the points value to compare with an integer to check if the user has enough point. get_points(user) > 10

The Code:

public async int get_points(string user){
 var client = new HttpClient();
 var request = new HttpRequestMessage
 {
    Method = HttpMethod.Get,
    RequestUri = new 
    Uri("https://api.streamelements.com/kappa/v2/points/abcd/fgh"),
    Headers =
    {
        { "Accept", "application/json" },
        { "Authorization", "Bearer 123" },
    },
  };
 using (var response = await client.SendAsync(request))
 {
    response.EnsureSuccessStatusCode();
    var result = await response.Content.ReadAsStringAsync();

    JObject jObj = JObject.Parse(result);
    Console.WriteLine(jObj["points"]);

    return jObj["points"].ToObject<int>();
 }
}

Error : the return type of an async method must be void.

You can use Task<int>

Like this

public async Task<int> get_points(string user){
    var client = new HttpClient();
    var request = new HttpRequestMessage
    {
        Method = HttpMethod.Get,
        RequestUri = new 
        Uri("https://api.streamelements.com/kappa/v2/points/abcd/fgh"),
        Headers =
        {
            { "Accept", "application/json" },
            { "Authorization", "Bearer 123" },
        },
    };
    using (var response = await client.SendAsync(request))
    {
        response.EnsureSuccessStatusCode();
        var result = await response.Content.ReadAsStringAsync();

        JObject jObj = JObject.Parse(result);
        Console.WriteLine(jObj["points"]);

        return jObj["points"].ToObject<int>();
    }
}

Note that you will also need to make sure to await the get_points method when calling it, as it is an async method.

int points = await get_points(user);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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