c# - StreamReader与using语句的区别?

标签 c# asp.net-core streamreader using

我正在使用 StreamReader,如下所示在我的代码中:

string json = await new StreamReader(context.Request.Body).ReadToEndAsync();
// ... use json variable here in some other code

我偶然发现了 using 语句。我的第一条语句与使用 using 语句与 StreamReader 之间有什么区别吗?

我应该在产品代码中使用 using 语句和 StreamReader 吗?

        string json;
        using (var reader = new StreamReader(context.Request.Body))
        {
            json = await reader.ReadToEndAsync();
        }

最佳答案

Is there any difference between my first statement vs using the using statement with StreamReader

是的。区别在于,当您将 StreamReader 包装在 using 中时声明它会直接清理一些资源,而不是等待垃圾收集器。更具体地说,它将调用 StreamReader 上的 Dispose()。当类实现 IDisposable 时,您几乎应该始终使用 using .

If your app simply uses an object that implements the IDisposable interface, you should call the object's IDisposable.Dispose implementation when you are finished using it.

由于 .NET Core 是开源的,我们可以看看 the source对于StreamReader:

protected override void Dispose(bool disposing)
{
    if (m_stream != null)
    {
        if (disposing)
        {
            m_stream.Close();
        }

        m_stream = null;
        m_buffer = null;
        m_curBufPos = 0;
        m_curBufLen = 0;
    }

    m_disposed = true;
}

如您所见,它在流上调用 Close(),而流 ( according to the docs ) 又会在流本身上调用 Dispose()

在处理较大的对象或流时,正确处理对象可能至关重要。不过,我会尝试针对您的其他问题。

Should I be using using statement with StreamReader here in prod code?

是的,不,也许。在您的具体情况下,您有一个 context.Request.Body 作为 Stream (我假设是来自HttpContext)。 StreamReader 不需要关闭该特定流。无论如何它都会被正确处理(稍后)。此外,可能还有一些其他资源需要稍后在管道中访问该特定流。

通常,如果类实现了 IDisposable,那么您应该将其包装在 using 中。但在这里我认为你有两个更好的选择:

1. 如果您实际上有一个 json (正如您的变量所建议的那样),您可以直接使用 JsonSerializer 反序列化它。在System.Text.Json.JsonSerializer中找到:

YourModel model = await System.Text.Json.JsonSerializer.DeserializeAsync<YourModel>(context.Request.Body);

更新: 或者,如果您使用的是 .NET 5,则可以访问 HttpResponseJsonExtensions并可以使用ReadFromJsonAsync 。然后您可以简单地尝试以下操作:

YourModel model = await context.Request.ReadFromJsonAsync<YourModel>();

感谢caius-jard .

2. 使用overload of StreamReader 不会关闭流。

string json;
using (var reader = new StreamReader(stream, Encoding.UTF8, true, -1, true))
{
    json = await reader.ReadToEndAsync();
}

所以,总结一下。是的,使用 using 时是有区别的。但是,根据您的具体情况,您有更好的选择。

关于c# - StreamReader与using语句的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69068974/

相关文章:

java - 在 Java 中通过 Bouncy CaSTLe 验证 pkcs7 SignedData

asp.net-core - Asp.Net core 中 FormDataCollection 的替代品是什么?

c# - 如何在 asp.net core 中使用 orchard .po 文件本地化来本地化数据注释属性?

c# - StreamReader ReadToEnd() 在第一次尝试时返回空字符串

c# - 解释峰值和标志算法

c# - 无法在 ItemSelector EXTJS 3 中显示所选项目

c# - 具有匿名类型的 IList 中的 Foreach

c# - 以 asp-for 作为参数的自定义 ViewComponent

c# - 如何从文本文件中读取特定行并将它们存储为字符串。 C#

c# - 读取非常大的文本文件,我应该合并异步吗?