我可以从SmtpClient.SendAsync的userToken对象中获得什么好处?

Nag*_*tri 14 c# sendmail smtpclient sendasync winforms

我用SMTPClient.Send(mail)的方法来发送电子邮件,但后来我看到,如果电子邮件ID不存在(不存在),我的应用程序等待,直到它接收到异常,然后允许用户执行其他任务.

所以我想到了使用SMTPClient.SendAsync方法.

我怀疑!! 这个userToken对象在哪里可以作为参数传递给方法?我在网上搜索了很多东西,但没有找到一个很好的例子.即使在MSDN中,他们也会这样使用它

string userState = "test message1";
client.SendAsync(message, userState);
Run Code Online (Sandbox Code Playgroud)

但那么它真正可以用于什么呢?

先感谢您.

Ale*_*kin 26

您可以在以下情况下使用它:假设您有批量电子邮件发送的应用程序.您撰写邮件(每个收件人的不同邮件\附件,因此您无法将其合并为单个邮件),例如选择20个收件人并按"全部发送"按钮.对于发送,您使用SendAsync和"池"中的几个SmtpClient实例(因为SmtpClient不允许在上一次调用未完成之前在一个实例上调用两次SendAsync).

对于所有SendAsync调用,您都应该有一个SmtpClientSendCompleted处理程序,您应该在其中执行高级日志记录:发送失败消息的收件人的发送,名称(地址甚至附件)的日志结果,但AsyncCompletedEventArgs只能在UserState的帮助下提供此信息.因此,用于此目的的基本模式是使用自定义用户状态对象.所以看看简化的例子:

包含处理程序中需要的字段的接口:

public interface IEmailMessageInfo{
   string RecipientName {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

异步状态类:

/// <summary>
/// User defined async state for SendEmailAsync method
/// </summary>
public class SendAsyncState {

    /// <summary>
    /// Contains all info that you need while handling message result
    /// </summary>
    public IEmailMessageInfo EmailMessageInfo { get; private set; }


    public SendAsyncState(IEmailMessageInfo emailMessageInfo) {
        EmailMessageInfo = emailMessageInfo;
    }
}
Run Code Online (Sandbox Code Playgroud)

这里是发送电子邮件的代码:

SmtpClient smtpClient = GetSmtpClient(smtpServerAddress);
smtpClient.SendCompleted += SmtpClientSendCompleted;
smtpClient.SendAsync(
   GetMailMessage()
   new SendAsyncState(new EmailMessageInfo{RecipientName = "Blah-blah"})
);
Run Code Online (Sandbox Code Playgroud)

和处理程序代码示例:

private void SmtpClientSendCompleted(object sender, AsyncCompletedEventArgs e){
    var smtpClient = (SmtpClient) sender;
    var userAsyncState = (SendAsyncState) e.UserState;
    smtpClient.SendCompleted -= SmtpClientSendCompleted;

    if(e.Error != null) {
       tracer.ErrorEx(
          e.Error, 
          string.Format("Message sending for \"{0}\" failed.",userAsyncState.EmailMessageInfo.RecipientName)
       );
    }

    // Cleaning up resources
    .....
}
Run Code Online (Sandbox Code Playgroud)

如果您需要更多详细信息,请告诉我们.