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

Time:01-02

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.

CodePudding user response:

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);
  • Related