强制关闭流

发布于 2024-11-15 03:39:23 字数 231 浏览 1 评论 0原文

我时常遇到问题,我的程序中有一些 StreamReaderStreamWriter 读取信息并写入信息。它们在大约 99% 的情况下都是正确的,但偶尔我会在一段我运行了多次的代码上得到一个无法关闭的 StreamWriter

如果我向某个功能发送垃圾邮件,这种情况往往会发生,但我正在尝试找到一种安全的方法来保证蒸汽得到处理。有人知道怎么做吗?

I have an issue from time to time, I have a few StreamReaders and StreamWriters in my program that read info and write it. They go right about 99% of the time, but once in a while I end up with a StreamWriter that won't close, on a piece of code I've run multiple times.

This tends to happen if I spam a function, but I am trying to find a safe way to guarantee a steam disposed. Anyone know how?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

极度宠爱 2024-11-22 03:39:23

尝试使用 using 语句 MSDN

using (StreamWriter stream = new StreamWriter(Initialization)){

   //your code

}

这可能很有用:

关闭流读取和流写入器表单退出

您也可以使用 Try

try
{
    //Declare your streamwriter
    StreamWriter sw = new StreamWriter(Initialization);
}
catch
{
    //Handle the errors
}
finally
{
    sw.Dispose();
}

try a using statement MSDN

using (StreamWriter stream = new StreamWriter(Initialization)){

   //your code

}

this can be useful:

Closing Stream Read and Stream Writer when the form exits

Also you could use a Try Block

try
{
    //Declare your streamwriter
    StreamWriter sw = new StreamWriter(Initialization);
}
catch
{
    //Handle the errors
}
finally
{
    sw.Dispose();
}
娇纵 2024-11-22 03:39:23

如果流的范围是本地的,请始终使用以下构造:

using (var stream = new Stream())
{
    ...do stream work here...
}

另一方面,如果您将流用作类字段,则实现 IDisposable 模式并在处置类时处置您的流对象:< a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="nofollow">IDisposable

If the stream's scope is local, always use the following construct:

using (var stream = new Stream())
{
    ...do stream work here...
}

If on the other hand you are using the stream as a class field then implement the IDisposable pattern and dispose your stream objects when disposing your class: IDisposable

暮倦 2024-11-22 03:39:23

将 StreamWriter 包装在 using 语句中是我通常确保它被处置的方式。

using (var writer = new StreamWriter(@"C:\AFile.txt"))
{
    //do some stuff with writer
}

另一种方法是使用finally 块。

Wrapping the StreamWriter in a using statement is how I usually ensure it is disposed of.

using (var writer = new StreamWriter(@"C:\AFile.txt"))
{
    //do some stuff with writer
}

An alternative would be to use a finally block.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文