gpt4 book ai didi

c# - 不在 .NET Core 中处理流

转载 作者:行者123 更新时间:2023-11-30 21:41:44 30 4
gpt4 key购买 nike

考虑 ASP.NET Core 的 ResponseBufferingMiddleware:

public class ResponseBufferingMiddleware
{
private readonly RequestDelegate _next;

public ResponseBufferingMiddleware(RequestDelegate next)
{
_next = next;
}

public async Task Invoke(HttpContext httpContext)
{
var originalResponseBody = httpContext.Response.Body;

// no-op if buffering is already available.
if (originalResponseBody.CanSeek)
{
await _next(httpContext);
return;
}

var originalBufferingFeature = httpContext.Features.Get<IHttpBufferingFeature>();
var originalSendFileFeature = httpContext.Features.Get<IHttpSendFileFeature>();
try
{
// Shim the response stream
var bufferStream = new BufferingWriteStream(originalResponseBody);
httpContext.Response.Body = bufferStream;
httpContext.Features.Set<IHttpBufferingFeature>(new HttpBufferingFeature(bufferStream, originalBufferingFeature));
if (originalSendFileFeature != null)
{
httpContext.Features.Set<IHttpSendFileFeature>(new SendFileFeatureWrapper(originalSendFileFeature, bufferStream));
}

await _next(httpContext);

// If we're still buffered, set the content-length header and flush the buffer.
// Only if the content-length header is not already set, and some content was buffered.
if (!httpContext.Response.HasStarted && bufferStream.CanSeek && bufferStream.Length > 0)
{
if (!httpContext.Response.ContentLength.HasValue)
{
httpContext.Response.ContentLength = bufferStream.Length;
}
await bufferStream.FlushAsync();
}
}
finally
{
// undo everything
httpContext.Features.Set(originalBufferingFeature);
httpContext.Features.Set(originalSendFileFeature);
httpContext.Response.Body = originalResponseBody;
}
}
}

实际文件链接:https://github.com/aspnet/BasicMiddleware/blob/dev/src/Microsoft.AspNetCore.Buffering/ResponseBufferingMiddleware.cs

为什么这不是内存泄漏?他们创建了一个新的 BufferingWriteStream ( https://github.com/aspnet/BasicMiddleware/blob/dev/src/Microsoft.AspNetCore.Buffering/BufferingWriteStream.cs ),但从不丢弃它。 HTTP 管道是否会在完成请求后自动处理流?

最佳答案

此流只是您在其构造函数中传递的其他流的包装器(在本例中为 originalResponseBody)。因此——没有必要处理它——它本身不包含任何它可以清除\释放的非托管资源,也不包含它应该处理的任何其他一次性组件,所以没有理由让它实现 IDisposable,但它继承自已经实现它的类。它只是将所有 Stream 方法(如 Read 等)代理到带有一些额外逻辑(缓冲)的包装流。

关于c# - 不在 .NET Core 中处理流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42985032/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com