如何复制 HttpContent 异步和可取消? [英] How to copy HttpContent async and cancelable?

查看:25
本文介绍了如何复制 HttpContent 异步和可取消?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HttpClient.PostAsync() 并且响应是 HttpResponseMessage.它的 Content 属性是 HttpContent 类型,它有一个 CopyToAsync() 方法.不幸的是,这是不可取消的.有没有办法将响应复制到 Stream 并传递 CancellationToken ?

I'm using HttpClient.PostAsync() and the response is an HttpResponseMessage. Its Content property is of type HttpContent which has a CopyToAsync() method. Unfortunately, this is not cancelable. Is there a way to get the response copied into a Stream and pass a CancellationToken?

我没有被 CopyToAsync() 困住!如果有办法解决就好了.比如读取几个字节,检查是否取消,继续读取等等.

I am not stuck with CopyToAsync()! If there is a workaround, that would be fine. Like read a couple of bytes, check if canceled, continue reading and so on.

HttpContent.CreateContentReadStreamAsync() 方法看起来像是一个候选方法.不幸的是,它不适用于我选择的个人资料.也不清楚会不会一次性读取所有数据,浪费大量内存.

The HttpContent.CreateContentReadStreamAsync() methods looks like it would be a candidate. Unfortunately, it's not available with my selected profile. Also unclear if it would read all data in one go and waste a lot of memory.

注意:我在针对 WP8、Windows Store 8、.NET 4.5、Xamarin.iOS 和 Xamarin.Android 的 PCL 中使用它

Note: I'm using this inside a PCL targeting WP8, Windows Store 8, .NET 4.5, Xamarin.iOS and Xamarin.Android

推荐答案

我相信这应该可行:

public static async Task DownloadToStreamAsync(string uri, HttpContent data, Stream target, CancellationToken token)
{
    using (var client = new HttpClient())
    using (var response = await client.PostAsync(uri, data, token))
    using (var stream = await response.Content.ReadAsStreamAsync())
    {
        await stream.CopyToAsync(target, 4096, token);
    }
}

请注意,ReadAsStreamAsync 调用 CreateContentReadStreamAsync,对于流响应,它只返回底层内容流,而不将其缓冲到内存中.

Note that ReadAsStreamAsync calls CreateContentReadStreamAsync, which for stream responses just returns the underlying content stream without buffering it into memory.

这篇关于如何复制 HttpContent 异步和可取消?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆