简体   繁体   English

Winrt / WP8.1中长时间轮询请求的巨大延迟

[英]Huge delay in long polling request in Winrt/WP8.1

I am writing universal app for Windows 8.1 and Windows Phone 8.1. 我正在为Windows 8.1和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. 我使用HttpClient进行此操作,并且工作正常,除了从流中获取新数据的巨大延迟之外。 On WinRT this delay about 10-20 secs and on Windows Phone its about 1-2 minutes(!!!). 在WinRT上,此延迟约为10-20秒,而在Windows Phone上,则约为1-2分钟(!!!)。 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());
                        }
                    }
                }
           }
     }
}

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 . 它无法正常工作,但是当它出现在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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM