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

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

问题描述

我用 HttpClient.PostAsync()和响应是的Htt presponseMessage 。其内容属性的类型为 HttpContent 具有 CopyToAsync()方法。不幸的是,这不是取消。 有没有办法让复制到流的响应,并通过的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应用商店8,.NET 4.5的PCL里面,Xamarin.iOS和Xamarin.Android

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天全站免登陆