Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long polling with Httpclient

I am consuming one REST API (GET) using .Net HttpClient. I want to call this API with long polling.

I have few questions:

  1. What is the best way to retrieve data using long polling?
  2. Here is my use case - my application will consume this api with long polling and based on results I will perform some operation on different thread. Based on new response of long poll get, I will abort/complete old thread and start operation on new thread again. How to achieve this using Tasks?
like image 516
Abhay Avatar asked Dec 31 '16 08:12

Abhay


1 Answers

For the first question I've found this solution, works pretty well:

var url = "http://your.url";
using (var client = new HttpClient())
{
    client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
    var request = new HttpRequestMessage(HttpMethod.Get, url);
    using (var response = await client.SendAsync(
        request, 
        HttpCompletionOption.ResponseHeadersRead))
    {
        using (var body = await response.Content.ReadAsStreamAsync())
        using (var reader = new StreamReader(body))
            while (!reader.EndOfStream)
                Console.WriteLine(reader.ReadLine());
    }
}
like image 130
Denis Gordin Avatar answered Nov 10 '22 01:11

Denis Gordin