Search code examples
c#restsharptimespan

How to run an api request until a condition is met in c#


I'm new to C# and my purpose is to parse a value from an API call and keep on doing the call until that value is between 5 and 10 for that parameter.

I have successfully parsed that value from valuez and got the proper result in finalresult, now my problem is to make the call repeatedly until I reach the intended value bracket, I tried debugging the code below but when it reaches var timer the entire block is highlighted at once and not every line is accessed separately. I know the condition of stopping between 5 and 10 is not in the code below but it was supposed to run endlessly before i modify that part.

sample response

{{
"value1" : "input1",
"value2" : null,
"value3" : {"valuex" : 4,
"valuey" : 5,
"valuez" : 6}
"value4" : 17
}}

,

Code

var options = new RestClientOptions(Endpoint)
double finalresult = -1;

var startTimeSpan = System.TimeSpan.Zero;
var periodTimeSpan = System.TimeSpan.FromMinutes(1);

var timer = new System.Threading.Timer(async(e) =>
{
var client = new RestClient(options);
vsr request = new RestRequest();
var response = await client.GetAsync(request);
var requestContent = response.Content;
var parsed = JsonConvert.DeserializeObject<StatusResponse>(responseContent);
finalresult = statusResponse.value3.valuez

}, null, startTimeSpan, periodTimeSpan);

Solution

  • I think this is what you need:

    public async Task<double> GetValuez()
    {
      var options = new RestClientOptions(Endpoint)
      double finalresult = -1;
    
      var startTimeSpan = System.TimeSpan.Zero;
      var periodTimeSpan = System.TimeSpan.FromMinutes(1);
      var client = new RestClient(options);
    
      while (true)
      {
        var request = new RestRequest();
        var response = await client.GetAsync(request);
        var requestContent = response.Content;
        var parsed = JsonConvert.DeserializeObject<StatusResponse>(responseContent);
        finalresult = statusResponse.value3.valuez
    
        if (finalresult >= 5 && finalresult <= 10) return finalresult;
    
        await Task.Delay(periodTimeSpan);
      }
    }
    

    It's a simple loop that will keep requesting until the condition is met.