使用StreamContent时如何正确处理流 [英] How to properly dispose the stream when using StreamContent

查看:33
本文介绍了使用StreamContent时如何正确处理流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从我的webapi端点返回流,然后通过处理该流进行清理.

I'm attempting to return a stream from my webapi endpoint, and then clean up by disposing the stream.

我希望这是正确的方法,但是流在返回之前就已经被处理掉了.

I expected this to be the correct way, but the stream is of course disposed before returning.

using(var stream = GetStream()){
    var response = new HttpResponseMessage();
    response.Content = new StreamContent(stream);

    return response;
}

处置流的正确方法是什么?

What will be the correct way of disposing the stream?

(由于MSDN对StreamContent的行为或其方法一无所知,所以我的临时解决方案是将流的内容复制到字节数组并返回它.)

(Since MSDN says nothing about the behaviour of StreamContent or its methods, my temporary solution is to copy the contents of the stream to a byte array and return that.)

推荐答案

由于唯一需要处置的资源就是 HttpResponseMessage 的内容,因此您不必担心.该框架为您处理.它将处置 HttpResponseMessage ,它将完成所有需要的处置.删除用法,它应该可以正常工作.

As your only resource that needs to be disposed is the Content of the HttpResponseMessage you don't have to worry about it. The framework does the dispose for you. It will dispose the HttpResponseMessage which will do all the disposing needed. Remove the using and it should work just fine.

当HttpResponseMessage被处理时,其内容将被处理.参见 .NET核心实现

The HttpResponseMessage will dispose its Content when it is disposed. See .NET Core implementation

StreamContent将在处置时处置其流.参见 .NETStreamContent的核心实现

The StreamContent will dispose its stream when it is disposed. See .NET Core implementation of StreamContent

如果您需要处置HttpResponseMessage未处置的内容,则可以使用 request.RegisterForDispose ,如

If you need to dispose something not disposed by the HttpResponseMessage you may use request.RegisterForDispose as described by Filip Woj

这篇关于使用StreamContent时如何正确处理流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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