2

Please see the bellow my code

HttpResponseMessage messge = client.GetAsync("ladders/get/"+ID+").Result;
if (messge.IsSuccessStatusCode)
{
   string result = messge.Content.ReadAsStringAsync().Result;
}

I need this code execute until "result" variable is not null or max 30 minutes. Every minute will be execute bellow code until (result !=null) within 30 minutes.

HttpResponseMessage messge = client.GetAsync("ladders/get/"+ID+").Result;

Let see, If don't get "result" value within 30 minutes then after 30 min function will be automatically stop & notify to user that value not found. Meanwhile user can access other page.

Please suggest me how can solve this issue .....

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Letoncse
  • 702
  • 4
  • 15
  • 36
  • Consider using a timer here. Have the interval at 1 minute, and cancel the timer if you reach 30 minutes or get a result. See https://stackoverflow.com/questions/1416803/system-timers-timer-vs-system-threading-timer for your options. I'd recommend System.Threading.Timer for your purpose. Also be aware that Timer tick events can overlap if your tick handler takes too long. – Warty Feb 15 '15 at 08:18
  • If we're talking about web dev then consider performing the above logic with something like setTimeout/setInterval, polling the webserver every minute. – Warty Feb 15 '15 at 08:24

1 Answers1

4

I'd first advise you not to block using .Result. The API's exposed by HttpClient are asynchronous by nature. By using it you may introduce deadlocks in your code which you probably don't want.

Basically, what you want to implement is a "first task wins" operation. For this, as HttpClient.GetAsync already returns a Task, you can another task to it which uses Task.Delay which internally uses a timer. And, you'll await whichever task completes first:

public async Task GetAsync()
{
    var expirationTimeTask = Task.Delay(TimeSpan.FromMinutes(30));
    var responseTask = client.GetAsync("ladders/get/ " + ID);

    var finishedTask = await Task.WhenAny(expirationTimeTask, responseTask);
    if (finishedTask == expirationTimeTask)
    {
        // If we get here, the timer passed 30 minutes
    }
    else
    {
        // If we get here, we got a response message first.
        if (responseTask.IsSuccessStatusCode)
        {
            string result = await responseTask.Content.ReadAsStringAsync();
        }   
    }
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321