Search code examples
c#windows-runtimewindows-phone-8.1httpclientlong-polling

Huge delay in long polling request in Winrt/WP8.1


I am writing universal app for Windows 8.1 and Windows Phone 8.1. I need to open long polling request to get continuously updating data stream. I doing this with HttpClient and its working fine, except of huge delay in getting new data from stream. On WinRT this delay about 10-20 secs and on Windows Phone its about 1-2 minutes(!!!). This is unacceptable for this app and i hope there is something wrong with my code and someone can help me to fix it. Here is my code:

var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
      client.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
      client.BaseAddress = new Uri("https://my.site.com/");
      handler.CookieContainer.SetCookies(client.BaseAddress, cookies);

      var link = "my/link";
      using (var tokenRequestMessage = new HttpRequestMessage(HttpMethod.Get, link))
      {
           tokenRequestMessage.Headers.Add("Authorization", token);
           tokenRequestMessage.Headers.Add("Foo", "Foo");
           tokenRequestMessage.Headers.Add("Foo1", "Foo2");
           var t = await client.SendAsync(tokenRequestMessage, HttpCompletionOption.ResponseHeadersRead);

           using (var httpResponse = t.Content)
           {
                using (var v = await httpResponse.ReadAsStreamAsync())
                {
                    using (var reader = new StreamReader(v))
                    {
                        while (!reader.EndOfStream)
                        {
                            Debug.WriteLine(reader.ReadLine());
                        }
                    }
                }
           }
     }
}

Solution

  • Well, here is the way how i accomplished my task. It's working not perfectly, but i getting data right away, when it appearing in InputStream.

    var uri = new Uri("www.example.com");
    using (var client = new Windows.Web.Http.HttpClient())
    {
      client.DefaultRequestHeaders.Cookie.ParseAdd(this.sessionCookies);
      client.DefaultRequestHeaders.Add("header", "value");
    
      var response = await client.GetAsync(uri, Windows.Web.Http.HttpCompletionOption.ResponseHeadersRead);
      var inputStream = await response.Content.ReadAsInputStreamAsync();
      IBuffer buffer = new Buffer(10000);
    
      do
      {
           buffer = await inputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.ReadAhead);
           var data = Encoding.UTF8.GetString(buffer.ToArray(), 0, (int) buffer.Length);
           Debug.WriteLine(data);                        
       } while (buffer.Length > 0);
    }