Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

asp.net - how to use threading

I am trying to send emails on a button click ...but I want to send the emails in the background as the number of emails are too many...so I am using threading..

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("[email protected]")
             message.To.Add(New MailAddress(_table.Rows(i).Item(1)))
             'message.CC.Add(New MailAddress("[email protected]"))
             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("[email protected]", "123456")
             'smtp.EnableSsl = True
             client.Send(message)
             i += 1
         Next
     Catch ex As Exception
         Response.Write(ex.Message)
     End Try
 End Sub

Table Structure

Sno
email
URL
ReporterName

I am using the below script in a button click event

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

Am i doing it right?? Because neither i get errors nor emails :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are better approaches than manually creating a thread.

I would first ensure that the actual send process is working in a single thread. Multithreaded applications are much harder to debug.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...