如何使用线程

时间:2012-03-17 08:43:26

标签: asp.net vb.net

我试图通过点击按钮发送电子邮件...但我想在后台发送电子邮件,因为电子邮件的数量太多......所以我使用的是线程...

Public Sub sendEmail()
     Dim _con As New SqlConnection(ConfigurationManager.ConnectionStrings("CitizenJDBConnectionString").ConnectionString)
     Dim _sqlDataAdapter As New SqlDataAdapter("SELECT * FROM EmailSender", _con)
     Dim _table As New System.Data.DataTable

     Try
         _con.Open()
         _sqlDataAdapter.Fill(_table)
         _con.Close()

         For i As Integer = 0 To _table.Rows.Count
             Dim AppPath As String = Request.PhysicalApplicationPath
             Dim sr As New StreamReader(AppPath & "EmailTemplates/NewReport.txt")
             Dim message As New MailMessage()

             message.IsBodyHtml = True
             message.From = New MailAddress("asdf@asdf.com")
             message.To.Add(New MailAddress(_table.Rows(i).Item(1)))
             'message.CC.Add(New MailAddress("monodeep12@gmail.com"))
             message.Subject = "New User registration !"
             message.Body = sr.ReadToEnd()
             sr.Close()
             message.Body = message.Body.Replace("<%ReporterName%>", _table.Rows(i).Item(3))
             message.Body = message.Body.Replace("<%ReportURL%>", _table.Rows(i).Item(2))

             Dim client As New SmtpClient()
             client.Host = "smtp.asdf.com"
             'smtp.gmail.com
             client.Port = 25
             client.UseDefaultCredentials = True
             client.Credentials = New System.Net.NetworkCredential("asdf@asdf.com", "123456")
             'smtp.EnableSsl = True
             client.Send(message)
             i += 1
         Next
     Catch ex As Exception
         Response.Write(ex.Message)
     End Try
 End Sub

表格结构

斯诺
电子邮件
URL
ReporterName

我在按钮点击事件中使用以下脚本

 Dim thread As New System.Threading.Thread(AddressOf sendEmail)
 Thread.IsBackground = True
 Thread.Start()
 Thread.Priority = System.Threading.ThreadPriority.Normal

我做得对吗?因为我既没有收到错误也没有收到电子邮件:(

1 个答案:

答案 0 :(得分:0)

有比手动创建线程更好的方法。

我首先要确保实际的发送过程在单个线程中运行。多线程应用程序更难调试。