妥善处理SmtpClient使用的资源 [英] Properly disposing resources used by SmtpClient

查看:220
本文介绍了妥善处理SmtpClient使用的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 C#服务连续运行与用户凭据(即不是本地系统 - 我不能改变,虽然我想)。在大多数情况下,服务似乎运行正常,但经常会弹出并且重新启动没有明显的原因(服务器管理器设置为重新启动服务崩溃)。

I have a C# service that runs continuously with user credentials (i.e not as localsystem - I can't change this though I want to). For the most part the service seems to run ok, but ever so often it bombs out and restarts for no apparent reason (servicer manager is set to restart service on crash).

我正在进行大量的事件日志记录,我有一个分层方法异常处理,我相信至少有一些意义:

I am doing substantial event logging, and I have a layered approach to Exception handling that I believe makes at least some sort of sense:


  • 本质上我得到了顶级通用异常,空异常和启动异常处理程序。

  • 然后我在命令级别处获得了各种处理程序(即服务运行的具体操作)

  • 最后我处理了在类级别处理的一些异常

  • Essentially I got the top level generic exception, null exception and startup exception handlers.
  • Then I got various handlers at the "command level" (i.e specific actions that the service runs)
  • Finally I handle a few exceptions handled at the class level

我一直在看, t正确发布,我开始怀疑我的邮件代码(发送电子邮件)。我注意到我没有调用Dispose for MailMessage对象,现在我已经重写了SendMail代码,如下所示。

I have been looking at whether any resources aren't properly released, and I am starting to suspect my mailing code (send email). I noticed that I was not calling Dispose for the MailMessage object, and I have now rewritten the SendMail code as illustrated below.

基本问题是:


  • 这个代码是否正确地释放了用于发送邮件的所有资源?

  • 我没有看到一个方法来处理 SmtpClient对象?

  • (为了记录:我没有使用对象初始化程序使样本更容易阅读)

  • will this code properly release all resources used to send mails?
  • I don't see a way to dispose of the SmtpClient object?
  • (for the record: I am not using object initializer to make the sample easier to read)
    private static void SendMail(string subject, string html)
    {
        try
        {
            using ( var m = new MailMessage() )
            {
                m.From = new MailAddress("service@company.com");
                m.To.Add("user@company.com");
                m.Priority = MailPriority.Normal;
                m.IsBodyHtml = true;
                m.Subject = subject;
                m.Body = html;
                var smtp = new SmtpClient("mailhost");
                smtp.Send(m);
            }
        }
        catch (Exception ex)
        {
            throw new MyMailException("Mail error.", ex);
        }
    }


推荐答案

知道这个问题是.Net 4之前的版本,但是现在版本4支持一个Dispose方法,它正确地发送一个退出到smpt服务器。请参阅 msdn reference 和< a href =https://stackoverflow.com/questions/2781103/c-how-to-correctly-dispose-of-an-smtpclient>较新的stackoverflow问题。

I know this question is pre .Net 4 but version 4 now supports a Dispose method that properly sends a quit to the smpt server. See the msdn reference and a newer stackoverflow question.

这篇关于妥善处理SmtpClient使用的资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆