我在调试时使用一段代码将一行信息写入文件。
private bool appendLine(string line2Write, string fileName)
{
try
{
StreamWriter tw;
using (tw = File.AppendText(fileName))
{
tw.WriteLine(line2Write);
tw.Close();
}
}
catch (Exception ex)
{
DialogResult result = MessageBox.Show("Unable to write to: " + fileName + "\r\n" + ex.ToString() + "\r\n OK to retry", "File Sysytem Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
if (result == DialogResult.Cancel)
{
return false;
}
}
return true;
}我不想让文件打开,因为如果它是调试信息,我不想冒险最后一点,如果程序崩溃。
我可能不明白CA2202在告诉我什么。
下面是整个错误声明:
警告CA2202对象'tw‘可以在方法'familyFinances.appendLine(string,string)’中多次释放。为了避免生成System.ObjectDisposedException,您不应该对对象调用Dispose超过一次。
"tw“只存在于此代码中。而且,我从来没有用这种方式运行过错误。
选择还是建议?
发布于 2018-10-04 17:35:59
正如其他人已经提到的,造成此问题是因为您正在using块中调用using,应该删除该调用。我建议你挖掘并理解为什么这些电话是等价的。
查看StreamWriter.Close()源代码:
public override void Close() {
Dispose(true);
GC.SuppressFinalize(this);
}以及IDisposable.Dispose()方法,TextWriter (BaseforStreamWriter)实现如下。当关闭Dispose()块的大括号时,运行时会调用该using。
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}编译器将using块转换为try/finally,因此所讨论的代码相当于:
StreamWriter tw = File.AppendText(fileName)
try {
tw.WriteLine(line2Write);
tw.Close();
}
finally {
tw.Dispose();
}所以你做了两次同样的事情,从而得到了警告。
FYI - .NET框架源代码这里
https://stackoverflow.com/questions/52650963
复制相似问题