如何遍历数据表的每一行以便为每一行一个接一个地执行功能

时间:2018-08-25 05:21:00

标签: c# .net foreach datatable

我在数据库中有一个表,该表具有单列和多行。我正在做的是遍历该表的每一行,并调用一个函数为每一行发送邮件。但是问题是该函数正在同时为所有行执行,而我想为每一行一个接一个地执行它。这是代码-

 protected void btnSubmit_Click(object sender, EventArgs e)
        {

            GetAllRecipient();
            Msg = null;
            ClientScript.RegisterStartupScript(GetType(), "alert", "alert('Email sent.');", true);

        }
     public void SendHTMLMail(string emailAddress)
            {
                MailMessage Msg = new MailMessage();
                SmtpClient smtp = new SmtpClient();
                Msg.To.Add(emailAddress);

           StreamReader reader = new StreamReader(Server.MapPath("~/one.html"));
                string readFile = reader.ReadToEnd();
                Regex regx = new Regex("(?<!src=\")http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?", RegexOptions.IgnoreCase);
                string output = regx.ToString();
                output = readFile;
                Msg.Body = output.ToString();
                Msg.IsBodyHtml = true;
                int i = 0;
                string username = Server.UrlEncode(this.txtUsername.Text);
                output = regx.Replace(output, new MatchEvaluator((match) =>
                {

                    var url = Uri.EscapeDataString(match.Value.ToString());
                    url = url.Replace("%3F", "&").Replace("%3D", "=");
                    return $"http://10.10.10.12/MI/two?sender={username}&link={url}&mailer_id={i}";
                }));
                Msg.From = new MailAddress(txtUsername.Text);
                Msg.Subject = null;
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential(txtUsername.Text, txtpwd.Text);
                smtp.EnableSsl = true;
                smtp.Send(Msg);
            }
            public void GetAllRecipient()
            {
                if (RadioButton1.Checked)
                {

                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "SELECT address FROM address1";
                    cmd.Connection = sql;
                    DataTable dt = new DataTable();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    sql.Open();
                    da.Fill(dt);
                    sql.Close();

                     //   for (int a = 0; a < dt.Rows.Count; a++)
                      //  {
                        foreach (DataRow row in dt.Rows)

                            {
                                SendHTMLMail(row["address"].ToString());

                            }

                       // }
                }

                else if (RadioButton2.Checked)
                {
                    string connectionString = "";
                    if (FileUpload1.HasFile)
                    {
                        string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                        string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                        string fileLocation = Server.MapPath("~/App_Data/" + fileName);
                        FileUpload1.SaveAs(fileLocation);

                        if (fileExtension == ".xls")
                        {

                            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                        }
                        else if (fileExtension == ".xlsx")
                        {
                            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                        }
                        OleDbConnection con = new OleDbConnection(connectionString);
                        OleDbCommand cmd = new OleDbCommand();
                        cmd.CommandType = System.Data.CommandType.Text;
                        cmd.Connection = con;
                        OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
                        DataTable dt = new DataTable();
                        con.Open();
                        DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
                        cmd.CommandText = "SELECT address FROM [" + getExcelSheetName + "]";
                        dAdapter.SelectCommand = cmd;
                        dAdapter.Fill(dt);
                        con.Close();


                      //  for (int a = 0; a < dt.Rows.Count; a++)
                       // {
                            foreach (DataRow row in dt.Rows)
                            {
                                SendHTMLMail(row["address"].ToString());

                            }

                      //  }
                    }
                }

1 个答案:

答案 0 :(得分:1)

您的代码中没有任何东西可以显示并发性或并行性。就目前而言,它应该为每行顺序执行而不是并发执行SendHTMLMail。是什么让您感觉这一切都在同时发生?还要验证SendHTMLMail的实现是否异步。