在登录代码后发送电子邮件会延迟网站



当用户登录我的asp.net网站失败时,我使用下面的代码发送电子邮件。电子邮件发送良好,但我注意到,在添加电子邮件功能后,网站对显示给用户的错误消息的响应速度较慢(变化约3-7秒)。

有没有办法让这些函数异步运行,这样就不会有延迟?

Protected Sub LoginUser_LoginError(ByVal sender As Object, ByVal e As System.EventArgs) Handles LoginUser.LoginError
    LoginUser.FailureText = "Invalid Username or Password - Please Try Again"
    Dim CurrentUser As MembershipUser = Membership.GetUser(LoginUser.UserName)
    If (CurrentUser IsNot Nothing) Then
        If (CurrentUser.IsLockedOut = True) Then
            LoginUser.FailureText = "Your account has been locked - Contact the system administrator"
        ElseIf (CurrentUser.IsApproved = False) Then
            LoginUser.FailureText = "Your account is disabled - Contact the system administrator"
        End If
        Dim mailobject As New System.Net.Mail.MailMessage()
        Dim myCred As New System.Net.NetworkCredential("info@domain.com", "password")
        mailobject.To.Add("myemail@domain.com")
        mailobject.Subject = CurrentUser.ToString() & " Failed Login"
        mailobject.From = New System.Net.Mail.MailAddress("from@domain.com")
        mailobject.IsBodyHtml = True
        mailobject.Body = "Event message: Membership credential verification failed."
        Dim SmtpMail As New System.Net.Mail.SmtpClient("smtp.domain.com")
        SmtpMail.UseDefaultCredentials = False
        SmtpMail.EnableSsl = False
        SmtpMail.Credentials = myCred
        SmtpMail.Port = 557
        SmtpMail.Send(mailobject)
    End If
End Sub

可能最简单的方法是启动一个新线程并从那里发送消息。这将是一场即发即弃。

如果我还记得我的VB.NET lambda语法,我相信它会看起来像:

Dim thread As New Thread(
    Sub() 
        ' Do the email stuff here
    End Sub
)
thread.Start()

ThreadSystem.Threading命名空间中,因此您需要:

Imports System.Threading

最新更新