[英]MemoryStream, XmlTextWriter and Warning 4 CA2202 : Microsoft.Usage
當使用MemoryStream
和XmlTextWriter
查看某個模式時,Visual Studio 2010 Ultimate中的“ 運行代碼分析”命令會返回警告。
這是警告:
警告7 CA2202:Microsoft.Usage:對象'ms'可以在方法'KinteWritePages.GetXPathDocument(DbConnection)'中多次處理。 為避免生成System.ObjectDisposedException,不應在對象上多次調用Dispose:Lines:421 C:\\ Visual Studio 2010 \\ Projects \\ Songhay.DataAccess.KinteWritePages \\ KinteWritePages.cs 421 Songhay.DataAccess.KinteWritePages
這是形式:
static XPathDocument GetXPathDocument(DbConnection connection)
{
XPathDocument xpDoc = null;
var ms = new MemoryStream();
try
{
using(XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8))
{
using(DbDataReader reader = CommonReader.GetReader(connection, Resources.KinteRssSql))
{
writer.WriteStartDocument();
writer.WriteStartElement("data");
do
{
while(reader.Read())
{
writer.WriteStartElement("item");
for(int i = 0; i < reader.FieldCount; i++)
{
writer.WriteRaw(String.Format("<{0}>{1}</{0}>", reader.GetName(i), reader[i].ToString()));
}
writer.WriteFullEndElement();
}
} while(reader.NextResult());
writer.WriteFullEndElement();
writer.WriteEndDocument();
writer.Flush();
ms.Position = 0;
xpDoc = new XPathDocument(ms);
}
}
}
finally
{
ms.Dispose();
}
return xpDoc;
}
為此表單生成了同樣的警告:
XPathDocument xpDoc = null;
using(var ms = new MemoryStream())
{
using(XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8))
{
using(DbDataReader reader = CommonReader.GetReader(connection, Resources.KinteRssSql))
{
//...
}
}
}
return xpDoc;
順便說一下,以下表格會產生另一個警告:
XPathDocument xpDoc = null;
var ms = new MemoryStream();
using(XmlTextWriter writer = new XmlTextWriter(ms, Encoding.UTF8))
{
using(DbDataReader reader = CommonReader.GetReader(connection, Resources.KinteRssSql))
{
//...
}
}
return xpDoc;
以上產生警告:
警告7 CA2000:Microsoft.Reliability:在方法“KinteWritePages.GetXPathDocument(DbConnection)”中,對象“ms”未沿所有異常路徑放置。 在對所有引用超出范圍之前,在對象'ms'上調用System.IDisposable.Dispose。 C:\\ Visual Studio 2010 \\ Projects \\ Songhay.DataAccess.KinteWritePages \\ KinteWritePages.cs 383 Songhay.DataAccess.KinteWritePages
除了以下內容,我有哪些選擇?:
MemoryStream
(因為Reflector沒有向我顯示源代碼)。 XDocument
和LINQ to XML。 首先,你永遠不應該使用new XmlTextWriter()
。 自.NET 2.0以來,它已被棄用。 請改用XmlWriter.Create()
。
其次, ms
的賦值應該在using塊中:
using (var ms = new MemoryStream())
{
using (var writer = XmlWriter.Create(ms))
{
// ...
}
}
我相信警告是正確的。 可以在放置XmlTextWriter
時處理MemoryStream
,然后再在“ finally
”塊中處理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.