हमारे पास कुछ (सिंक्रोनस) ईमेल कोड है, जो एक वर्ग बनाता है जो एक SmtpClient बनाता है, और उसके बाद एक ईमेल भेजता है। SmtpClient का पुन: उपयोग नहीं किया जाता है; लेकिन हम हर अब और फिर निम्न अपवाद प्राप्त करें:SmtpClient.Send को कॉल करते समय हमें समय-समय पर "एक असीमित कॉल पहले से प्रगति पर क्यों मिलता है"?
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidOperationException: An asynchronous call is already in progress. It must be completed or canceled before you can call this method.
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at EmailSender.SendMail(MailAddress fromMailAddress, string to, String subject, String body, Boolean highPriority) in ...\EmailSender.cs:line 143
कोड इस तरह दिखता है:
// ...
var emailSender = new EmailSender();
emailSender.SendMail(toEmail, subject, body, true);
// emailSender not used past this point
// ...
public class EmailSender : IEmailSender
{
private readonly SmtpClient smtp;
public EmailSender()
{
smtp = new SmtpClient();
}
public void SendMail(MailAddress fromMailAddress, string to, string subject, string body, bool highPriority)
{
if (fromMailAddress == null)
throw new Exception();
if (to == null)
throw new ArgumentException("No valid recipients were supplied.", "to");
// Mail initialization
var mailMsg = new MailMessage
{
From = fromMailAddress,
Subject = subject,
Body = body,
IsBodyHtml = true,
Priority = (highPriority) ? MailPriority.High : MailPriority.Normal
};
mailMsg.To.Add(to);
smtp.Send(mailMsg);
}
}
या बल्कि एक नया SmtpClient उदाहरण बनाने की तुलना में, ओपी सिर्फ इतना है कि वस्तु लॉक कर सकता संदेश भेजा जाता है जब तक। – Marco
हां कन्स्ट्रो में क्लाइंट बनाने का एक अच्छा कारण है: जब आप एक ही सर्वर कनेक्शन पर एकाधिक ईमेल भेज रहे हैं तो पूल किया जाएगा। Http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.dispose.aspx –
@EnnodeWeerd पर टिप्पणी अनुभाग देखें: अद्यतन कोड देखें। – jgauffin