如何使用线程 [英] how to use threading

查看:121
本文介绍了如何使用线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图发送一个按钮点击电子邮件...但我想发送的电子邮件在后台邮件数量太多...所以我使用的线程。

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("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

表结构

斯诺结果
电子邮件结果
网址结果
ReporterName

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 :(

推荐答案

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

There are better approaches than manually creating a thread.

  • SendAsync() method
  • Parallel libraries
  • ThreadPool

我想先确保实际的发送过程是在一个单独的线程工作。多线程应用程序更难调试。

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

这篇关于如何使用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆