How to understand C# SendAsync function?

893 views Asked by At

When i program with C# to send a mail by batch,my code is like this:

public static bool Send(MailAddress Messagefrom,
    string MessageTo,
    string MessageSubject,
    string MessageBody)
{
    MailMessage message = new MailMessage();
    message.From = Messagefrom;
    message.To.Add(MessageTo);
    message.Subject = MessageSubject;
    message.Body = MessageBody;            
    message.BodyEncoding = System.Text.Encoding.UTF8;
    //message.SubjectEncoding = Encoding.BigEndianUnicode;
    message.IsBodyHtml = true;
    message.Priority = MailPriority.High;            
    MailHelper mh = new MailHelper();
    SmtpClient sc = mh.setSmtpClient("smtp.qq.com", 25);   
    sc.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);  
    try
    {                
        sc.SendAsync(message, message);                
    }
    catch (Exception e)
    {
        LogHelper.WriteLog("Main send failed....\t the detail info:" + 
            e.ToString());
        return false;
    }
    return true;
}

This is a problem!When the first mail send failed(for example the mail address is null),the next mail can't be send!

Because i have so much mail wait to send,if this situation,how to fix it?For example the failed mail may still on this table and Administator to deal it by hand.

But this situation probably in Send function,Why this happen?

1

There are 1 answers

0
RononDex On

You have to catch errors in the foreach loop that calls your Send() function and log the errors somewhere:

foreach (var mail in mailsToSend)
{
    try
    {
        // Call your send function
        Send(...)
    }
    catch (Exception ex)
    {
        // Log the error somewhere (console, file, ...)
        Console.WriteLine("Error sending mail {0}", mail);
    }
}

This ensures that the application won't crash when one email fails to send and continue sending the other mails.

Also you should use Send() instead of SendAsync() in your Send() function. This is because the SendAsync function starts a new thread for sending the mail, while Send will stop your programs execution until the mail has been sent. One more reason you shouldn't use the SendAsync function is because according to microsoft only 1 mail can be send at a time. That means using the SendAsync function for more then 1 mail will cause it to throw an exception.