代码分析抱怨我没有处理对象。这里有什么问题吗?

发布于 2024-11-30 06:09:56 字数 1828 浏览 2 评论 0原文

考虑这段代码

private MailMessage GetMailMessageFromMailItem(Data.SystemX.MailItem mailItem)
        {

            var msg = new MailMessage();

            foreach (var recipient in mailItem.MailRecipients)
            {
                var recipientX = Membership.GetUser(recipient.UserKey);
                if (recipientX == null)
                {
                    continue;
                }

                msg.To.Add(new MailAddress(recipientX.Email, recipientX.UserName));
            }

            msg.From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"],
                                   ConfigurationManager.AppSettings["EmailSenderName"]);

            msg.Subject = sender.UserName;
            if (!string.IsNullOrEmpty(alias)) msg.Subject += "(" + alias + ")";
            msg.Subject += " " + mailItem.Subject;
            msg.Body = mailItem.Body;
            msg.Body += Environment.NewLine + Environment.NewLine + "To reply via Web click link below:" + Environment.NewLine;
            msg.Body += ConfigurationManager.AppSettings["MailPagePath"] + "?AID=" + ContextManager.AccountId + "&RUN=" + sender.UserName;

            if (mailItem.MailAttachments != null)
            {
                foreach (var attachment in mailItem.MailAttachments)
                {
                    msg.Attachments.Add(new Attachment(new MemoryStream(attachment.Data), attachment.Name));
                }
            }

            return msg;
        }

,我只是将我的数据库类型转换为 MailMessage。 它在另一个函数中发送。

代码分析告诉我我没有处理“msg”,这是正确的。但如果我在这里这样做 - 当我尝试发送它时我会遇到异常。

另外,它还抱怨没有在这里处理 MemoryStream:

msg.Attachments.Add(new Attachment(new MemoryStream(attachment.Data), 附件.名称));

我不知道如何正确处置它。我尝试了不同的方法,但在发送邮件时遇到异常“流已关闭”

Consider this code

private MailMessage GetMailMessageFromMailItem(Data.SystemX.MailItem mailItem)
        {

            var msg = new MailMessage();

            foreach (var recipient in mailItem.MailRecipients)
            {
                var recipientX = Membership.GetUser(recipient.UserKey);
                if (recipientX == null)
                {
                    continue;
                }

                msg.To.Add(new MailAddress(recipientX.Email, recipientX.UserName));
            }

            msg.From = new MailAddress(ConfigurationManager.AppSettings["EmailSender"],
                                   ConfigurationManager.AppSettings["EmailSenderName"]);

            msg.Subject = sender.UserName;
            if (!string.IsNullOrEmpty(alias)) msg.Subject += "(" + alias + ")";
            msg.Subject += " " + mailItem.Subject;
            msg.Body = mailItem.Body;
            msg.Body += Environment.NewLine + Environment.NewLine + "To reply via Web click link below:" + Environment.NewLine;
            msg.Body += ConfigurationManager.AppSettings["MailPagePath"] + "?AID=" + ContextManager.AccountId + "&RUN=" + sender.UserName;

            if (mailItem.MailAttachments != null)
            {
                foreach (var attachment in mailItem.MailAttachments)
                {
                    msg.Attachments.Add(new Attachment(new MemoryStream(attachment.Data), attachment.Name));
                }
            }

            return msg;
        }

I'm just taking my database type and converting to MailMessage.
It get's sent in another function.

Code analysis tells me I'm not disposing "msg" which is correct. But if I do it here - I get exception when I'm trying to send it.

Also, it complains about not disposing MemoryStream here:

msg.Attachments.Add(new Attachment(new MemoryStream(attachment.Data),
attachment.Name));

I have no idea on how to properly dispose it. I tried different things but was getting exceptions when sending mail saying "Stream is closes"

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

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

发布评论

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

评论(3

荒岛晴空 2024-12-07 06:09:56

基本上你不应该 - 稍后处理邮件消息将处理每个附件,这将处理每个流。此外,未能处理未在远程处理中使用的 MemoryStream 不会造成任何损害。

我建议您抑制此方法的警告。

编辑:我怀疑您可以使用 [SuppressMessage] 抑制该消息。


请注意,某些代码可能会在方法中途抛出代码,因此即使调用代码中有 using 语句,您最终也永远无法处理该消息。如果你真的很烦恼,你可以写:

private MailMessage GetMailMessageFromMailItem(Data.SystemX.MailItem mailItem)
{
    bool success = false;
    var msg = new MailMessage();
    try
    {
        // Code to build up bits of the message
        success = true;
        return msg;
    }
    finally
    {
        if (!success)
        {
            msg.Dispose();
        }
    }
}

不过就我个人而言,我认为这有点过分了。

Basically you shouldn't - disposing of the mail message later will dispose of each attachment, which will dispose of each stream. Besides, failing to dispose of a MemoryStream which isn't being used in remoting won't do any harm.

I suggest you suppress the warning for this method.

EDIT: I suspect you can use [SuppressMessage] to suppress the message.


Note that there's a risk that some code will throw code half way through the method, so you end up never being able to dispose of the message even if you have a using statement in the calling code. If you're really bothered, you could write:

private MailMessage GetMailMessageFromMailItem(Data.SystemX.MailItem mailItem)
{
    bool success = false;
    var msg = new MailMessage();
    try
    {
        // Code to build up bits of the message
        success = true;
        return msg;
    }
    finally
    {
        if (!success)
        {
            msg.Dispose();
        }
    }
}

Personally I'd say this is overkill though.

爱的那么颓废 2024-12-07 06:09:56

关于“不处理“msg””,我能想到的唯一方法是不返回 MailMessage,而是传递对 MailMessage 的引用。
像这样的东西。不确定这是否是一个好主意。

private void GetMailMessageFromMailItem(ref MailMessage msg, Data.SystemX.MailItem mailItem)

With regards to "not disposing "msg"", the only way I can think of is instead of returning MailMessage rather pass in a reference to a MailMessage.
Something like this. Not sure if it's such a good idea.

private void GetMailMessageFromMailItem(ref MailMessage msg, Data.SystemX.MailItem mailItem)
鲸落 2024-12-07 06:09:56

一次性物品的创造者也应该处置它。如果您无法在此处处理消息,则应将其从其他地方的创建者传入。在这种情况下,代码分析是正确的,如果您忽略这些消息,您可能会遇到非常不幸且难以调试的泄漏。

The creator of the disposable object should also dispose it. If you can't dispose the message here then it should be passed in from a creator somewhere else. Code analysis is right in this case and you can end up with very unfortunate and hard to debug leaks if you ignore these messages.

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