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

时间:2014-04-19 15:07:20

标签: asp.net vb.net

当用户登录我的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

1 个答案:

答案 0 :(得分:-1)

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

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

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

Thread位于System.Threading命名空间中,因此您需要:

Imports System.Threading