首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CA2000:释放对象警告

CA2000:释放对象警告
EN

Stack Overflow用户
提问于 2018-02-12 10:54:12
回答 2查看 1.8K关注 0票数 0

我有以下方法:

代码语言:javascript
复制
    public byte[] HtmlToDoc(string hmtl, string userId)
    {
        byte[] data;
        var auditor = new ServiceAuditor
        {
            User = userId
        };
        try
        {
            using (var tx = new ServerText())
            {
                tx.Create();
                tx.Load(Server.HtmlDecode(hmtl), StringStreamType.HTMLFormat);
                tx.Save(out data, BinaryStreamType.MSWord);
            }
        }
        catch (Exception e)
        {
            auditor.Errormessage = e.Message + "/n " + e.StackTrace;
            data = new byte[0];
        }
        finally
        {
            auditor.Save();
            auditor.Dispose();
        }
        return data;
    }

在编译过程中,我收到以下警告:

警告CA2000: Microsoft.Reliability :在方法'DocCreator.HtmlToDoc(string,string)‘中,对象'new ()’不是沿所有异常路径释放的。在所有对对象的引用超出作用域之前,在对象'new ()‘上调用ServiceAuditor。

奇怪的是,我不明白为什么它在抱怨,即使我正在处理这个物体。你能指出问题在哪里吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-02-12 11:15:44

问题是这句话:

代码语言:javascript
复制
auditor.Save();

如果这引发异常,则下一行将不会运行负责处理auditor对象的代码。因此,您可以将Save调用包装在另一个try/catch中,但实际上您应该只依赖using语句来执行此操作,因为它隐式调用了Dispose方法,例如:

代码语言:javascript
复制
public byte[] HtmlToDoc(string hmtl, string userId)
{
    byte[] data;

    //Add using statement here and wrap it around the rest of the code
    using(var auditor = new ServiceAuditor { User = userId })
    {
        try
        {
            using (var tx = new ServerText())
            {
                tx.Create();
                tx.Load(Server.HtmlDecode(hmtl), StringStreamType.HTMLFormat);
                tx.Save(out data, BinaryStreamType.MSWord);
            }
        }
        catch (Exception e)
        {
            auditor.Errormessage = e.Message + "/n " + e.StackTrace;
            data = new byte[0];
        }
        finally
        {
            auditor.Save();
            //No need to manually dispose here any more
        }
    }

    return data;
}
票数 5
EN

Stack Overflow用户

发布于 2018-02-12 15:15:46

谢谢@DavidG对您的响应,在提到的行中肯定有一个错误点,但是引起警告的是对象的初始化:

代码语言:javascript
复制
//Add using statement here and wrap it around the rest of the code
using(var auditor = new ServiceAuditor { User = userId })
{
    try
    { ...

应:

代码语言:javascript
复制
using(var auditor = new ServiceAuditor())
{
   auditor.User = userId;
    try
    { ...

我在这里找到了这个问题的参考资料,CA2000:处置。

不应在using语句的构造函数中初始化一次性对象的成员。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48744738

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档