Quantcast nên Disposable SmtpClient object khi sử dụng .net 4.0

nên Disposable SmtpClient object khi sử dụng .net 4.0

by Neon Quach 8. July 2011 21:52

Mặc định trình "thu lụm rác" (Garbage Collection) trong Visual studio sẻ tự động hủy object, sau khi nó không còn được reference nửa, nếu muốn tự tay mình disposable object sau khi object đó ra khỏi phạm vi sử lý nửa thì thường chúng ta wrap chúng trong using statement like:

using(object obj = new object())
{
.......
}


Trong version 3.5 trước của Net framework, khi chúng ta sử dụng object SmtpClient thì object này không inherit từ IDisposable nên chúng ta không thể bọc object trong using statement được. Nhưng đối với .net 4.0 thì chúng ta có thể làm được điều đó.

   
public string SendMail(string subject, string body, string to, bool isHtml, bool isSSL)
    {
        try
        {
            using (MailMessage mail = new MailMessage())
            {
                mail.From = new MailAddress(FormAddress, "code2code.info");
                mail.To.Add(to);
                mail.Subject = subject;
                mail.Body = body;
                mail.IsBodyHtml = isHtml;
                using (SmtpClient client = new SmtpClient())
                {
                    client.EnableSsl = isSSL;
                    if (FileUpload1.HasFile)
                    {
                        mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName));
                    }
                    client.Send(mail);
                }
            }
        }
        catch (SmtpException ex)
        {
            return ex.Message;
        }
        return "Send email successful!";
    }


Nếu chúng ta build với StyleCop enable thì sẻ cảnh báo message này:

Warning    20    CA2000 : Microsoft.Reliability : In method 'TestEmail.btnSendTest_Click(object, EventArgs)', call System.IDisposable.Dispose on object 'new SmtpClient()' before all references to it are out of scope.

Note: việc quản lý object bằng cách hủy chúng đi khi không còn reference nửa, rất quan trọng trong vấn đề cải thiện tốc độ cho ứng dụng, chúng ta nên warp tất cả các đối tượng nào kế thừa từ IDisposable.

Hope this help.

Tags: , , , ,


Categories: asp.net | visual studio 2010 | visual studio tips | c# | refactoring

blog comments powered by Disqus

About me

I'm  currently employed as Software developer at devinition.com and also a Microsoft Certified Technology Specialist (MCTS), Microsoft Certified Professional Developer (MCPD) in Net Framework 2.0 and 3.5: Web Applications and MCTS .NET Framework 3.5, ADO.NET Applications

Powered by BlogEngine.NET 2.5.0.5 - Eco Theme by n3o Web Designers