注意:我已经阅读了以下两个问题:
你能解释一下流的概念吗?
C# 使用流
我正在用 C# 编写代码
我目前正在我的应用程序中构建一个类,其中包含一个主要方法(我们称之为 GetStream()
),该方法通过 myWebRequest.GetResponse().GetResponseStream() 返回一个流
主要方法 GetStream()
返回一个 Stream
对象,该对象可用于任何需要流的操作(StreamReader、Bitmap() 等).>
有没有办法让流在上次使用后自动处理(垃圾收集?),而不强制任何调用 .GetStream()
的人手动处理它?</p>
您可能已经知道,我的问题很笼统.我对流的理解并不扎实,因此,如果提供比 SO 问题更深入地了解流的有用文章的链接,我们将不胜感激.
处理流会关闭它(并且可能不会做太多其他事情.)关闭流会刷新它,并释放与流相关的任何资源,例如文件句柄.刷新流会获取任何尚未写入的缓冲数据,并立即将其写出;一些流在内部使用缓冲来避免对相对昂贵的资源(如磁盘文件或网络管道)进行大量小更新.
您需要在大多数流上调用 Close
或 Dispose
,否则您的代码不正确,因为基础资源不会被释放给其他人使用,直到垃圾收集器来了(谁知道这需要多长时间.)Dispose
是理所当然的首选;预计您将在 C# 中处理所有一次性物品.在大多数情况下,您可能不必显式调用 Flush
.
在 C# 中,通过 using
块调用 Dispose
是惯用的方式,这是在 finally 中处理的 try-finally 块的语法糖,例如:
using (FileStream stream = new FileStream(path)){//...}
在功能上与
相同FileStream 流;尝试{流 = 新文件流(路径);//...}最后{如果(流!= null)流处理();}
Note: I've read the following two questions already:
Can you explain the concept of streams?
C# using streams
I'm coding in C#
I'm currently building a class in my application that contains a primary method (lets call it GetStream()
) that returns a stream via myWebRequest.GetResponse().GetResponseStream()
The primary method GetStream()
returns a Stream
object that can be used for any operation that requires a stream (StreamReader, Bitmap() etc.).
Is there a way to have the stream Disposed of automatically after its last use (garbage collected?) without forcing anyone that calls .GetStream()
to manually dispose of it?
As you can probably tell, my questions are vague and general. My understanding of streams is not solid, so any links to helpful articles that offer a more in-depth look at streams than a SO question can offer would be appreciated.
Disposing a stream closes it (and probably doesn't do much else.) Closing a stream flushes it, and releases any resources related to the stream, like a file handle. Flushing a stream takes any buffered data which hasn't been written yet, and writes it out right away; some streams use buffering internally to avoid making a ton of small updates to relatively expensive resources like a disk file or a network pipe.
You need to call either Close
or Dispose
on most streams, or your code is incorrect, because the underlying resource won't be freed for someone else to use until the garbage collector comes (who knows how long that'll take.) Dispose
is preferred as a matter of course; it's expected that you'll dispose all disposable things in C#. You probably don't have to call Flush
explicitly in most scenarios.
In C#, it's idiomatic to call Dispose
by way of a using
block, which is syntactic sugar for a try-finally block that disposes in the finally, e.g.:
using (FileStream stream = new FileStream(path))
{
// ...
}
is functionally identical to
FileStream stream;
try
{
stream = new FileStream(path);
// ...
}
finally
{
if (stream != null)
stream.Dispose();
}
这篇关于了解流及其生命周期(Flush、Dispose、Close)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!