简体   繁体   English

我是否应该关心StreamWriter.Dispose()是否抛出System.IO.IOException?

[英]Should I care if StreamWriter.Dispose() throws a System.IO.IOException?

I'm using a StreamWriter to write to a file over the network (Samba). 我正在使用StreamWriter通过网络(Samba)写入文件。

Sometimes, the network conditions are not so good and causes my write to fail. 有时,网络条件不是很好,并导致我的写入失败。 In that case, I want to just clean up and try starting a new file. 在这种情况下,我只想清理并尝试启动一个新文件。

The problem is that, even when I try to clean up (ie calling Dispose() on my StreamWriter object), I get an IOException as it fails to flush (because the network conditions are bad, remember), like so: 问题是,即使当我尝试清理(即在StreamWriter对象上调用Dispose())时,我也会收到IOException,因为它无法刷新(因为网络条件不好,请记住),如下所示:

System.IO.IOException
An unexpected network error occurred.

   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.FlushWrite(Boolean calledFromFinalizer)
   at System.IO.FileStream.Flush(Boolean flushToDisk)
   at System.IO.StreamWriter.Dispose(Boolean disposing)
   at System.IO.TextWriter.Dispose()

Shall I care in such case? 在这种情况下我可以照顾吗? If I catch the IOException, shall I then try to somehow finish the clean up in other ways? 如果我捕获了IOException,是否应该尝试以其他方式完成清理? Or do I just ignore the IOException and move along? 还是我只是忽略IOException而继续前进?

In other words, what should I do here? 换句话说,我应该在这里做什么?

try
{
    using (StreamWriter writer = new StreamWriter(some_network_file_path, /* ... */))
    {
        while (true)
        {
            /* append lines of csv-style data to the file. */
        }
    }
}
/* writer.Dispose() can throw an IOException as it fails to flush. */
catch (System.IO.IOException)
{
    /*
    What shall I do here, if anything at all?
    Suppose that my only concern is resource leak via the StreamWriter
    object.
    It's easy for me to clean up the data file later by discarding the last
    incomplete line.
    */
}

You should care about an error if you, well, care about: 你应该关心一个错误,如果你,好了, 在乎

  • whether it happens or not, and 是否发生,以及
  • the fact of it happening when it does. 事实确实如此。

The first thing to make clear for yourself here is the cause(s) of the error and the resulting impact of it happening or not happening on your application. 在这里首先要弄清楚自己的原因是错误的原因以及对您的应用程序发生或未发生错误的后果

Eg if your I/O failed, you sigh and think your data is lost. 例如,如果您的I / O失败,您会叹气并认为数据已丢失。 But, on connection close (if your deduction is correct), a flush is attempted again, and if there's no error this time, your data actually isn't lost. 但是,在连接关闭时(如果您的推论是正确的),将再次尝试刷新,并且如果这次没有错误,则您的数据实际上不会丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM