首页 > 解决方案 > 流 ReadAsStreamAsync (ReadTimeout = Timeout.Infinite) + json = 此流不支持超时。

问题描述

我需要发送一个 post HTTP 请求,并将 json 结果转换为 IEnumerable。

到目前为止我所拥有的:

  public IEnumerable<T> GetDataStream<T>(string baseURL, string query, string HTTPMethod) where T : IEntity, new()
    {
        var stopWatch = new Stopwatch();
        log.Info($"HttpMethod : [{HTTPMethod}] - Query: {query}");
        stopWatch.Start();
        var handler = new HttpClientHandler { UseDefaultCredentials = true };
        var client = new HttpClient(handler) { Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite) };
        var requestMethod = HTTPMethod == "GET" ? HttpMethod.Get : HttpMethod.Post;
        var request = new HttpRequestMessage(requestMethod, requestMethod == HttpMethod.Get ? $"{baseURL}?query={query}" : baseURL);
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage response;
        var tokenSource = new CancellationTokenSource();
        tokenSource.CancelAfter(TimeSpan.FromMilliseconds(Timeout.Infinite));
        if (requestMethod == HttpMethod.Get)
        {
            response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, tokenSource.Token).Result;
        }
        else
        {
            var content = new StringContent(query, Encoding.UTF8, "application/json");
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            response = client.PostAsync(baseURL, content, tokenSource.Token).Result;
        }

        response.EnsureSuccessStatusCode();
        using (var stream = response.Content.ReadAsStreamAsync().Result)
        {
            stream.ReadTimeout = Timeout.Infinite;
            using (var sr = new StreamReader(stream, Encoding.UTF8))
            using (var jr = new JsonTextReader(sr))
            {
                var serializer = new JsonSerializer();
                while (jr.Read())
                {
                    if (jr.TokenType != JsonToken.StartArray && jr.TokenType != JsonToken.EndArray)
                    {
                        yield return serializer.Deserialize<T>(jr);
                    }
                }
            }
        }

        stopWatch.Stop();
        log.Debug($"Total time : {stopWatch.Elapsed:m\\:ss\\.ff}");
    }

但我面临以下错误:

System.InvalidOperationException: 'Timeouts are not supported on this stream.'

这是来自这一行:

 stream.ReadTimeout = Timeout.Infinite;

我认为这是因为我还将这段代码与 JSON Deserialize 调用相结合。我不知道如何为此流使用无限超时。

标签: c#jsonasynchronousstreamreader

解决方案


推荐阅读