确保在每次执行方法

时间:2016-10-19 00:12:46

标签: c# listview datagridview

我创建了一个方法,将数据从数据库提取到datagridview,并从datagridview中提取,这是一种发送电子邮件的方法。我这样编码:

 // TODO: Prepare the email addresses
        private void SendEmail()
        {
            // Get the email addresses according to bio_id
            var rdr = new EmployeeDataAccess().GetBioIdEmail();
            while (rdr.HasRows && rdr.Read())
            {
                dgvBioIdList.Rows.Add(rdr["bio_id"].ToString(), rdr["email_add"].ToString());
            }

            // Get the time logs for each of the bio_id in the datagridview
            Cursor.Current = Cursors.WaitCursor;
            for (var i = 0; i < dgvBioIdList.Rows.Count; i++)
            {
                using (var cn = new DatabaseConnection().ConnectToMySql())
                {
                    const string query = @"SELECT MIN(scan_time) as 'TimeIn', MAX(scan_time) as 'TimeOut', 
                    TIMEDIFF(MAX(scan_time),MIN(scan_time)) as difference 
                    FROM `filtered_dates` 
                    WHERE date BETWEEN @fromDate AND @toDate AND bio_id = @bioId
                    GROUP BY date 
                    ORDER BY date asc";
                    var cmd = new MySqlCommand(query, cn);
                    cn.Open();
                    cmd.Parameters.AddWithValue("@fromDate", dtpStart.Text);
                    cmd.Parameters.AddWithValue("@toDate", dtpStop.Text);
                    cmd.Parameters.AddWithValue("@bioId", dgvBioIdList.Rows[i].Cells[0].Value);
                    rdr = cmd.ExecuteReader();

                    // Create the message to send to the email
                    if (!rdr.HasRows) continue;
                    var message = "Time Logs for Bio ID: " + dgvBioIdList.Rows[i].Cells[0].Value;
                    message += Environment.NewLine;
                    message += @"Included dates: " + dtpStart.Text + @" to " + dtpStop.Text;
                    message += Environment.NewLine;
                    message += @"Email Address: " + dgvBioIdList.Rows[i].Cells[1].Value;
                    message += Environment.NewLine;
                    while (rdr.Read())
                    {
                        message += rdr["TimeIn"] + @" - " + rdr["TimeOut"] +@" = " +rdr["Difference"];
                        message += Environment.NewLine;
                    }

                    // Actual sending of the email
                    SendingEmail(dgvBioIdList.Rows[i].Cells[0].Value.ToString(),dgvBioIdList.Rows[i].Cells[1].Value.ToString(), message, txtUserName.Text, txtPassword.Text);
                }
            }
            Cursor.Current = Cursors.Default;
        }

        // Sending of the E-mail and to list the status of the sending in a listview
        private void SendingEmail(string bioId, string recipient, string body, string userName, string password)
        {
            var mail = new MailMessage();
            var smtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress(userName);
            mail.To.Add(recipient);
            mail.Subject = "Time Logs";
            mail.Body = body;

            smtpServer.Port = 587;
            smtpServer.Credentials = new System.Net.NetworkCredential(userName, password);
            smtpServer.EnableSsl = true;
            try
            {
                smtpServer.Send(mail);
                string[] row = {bioId, recipient, "PASSED"};
                var listViewItem = new ListViewItem(row);
                lvEmailStatus.Items.Add(listViewItem);
                //Console.WriteLine(@"Successfully sent mail to " + recipient);
            }
            catch (Exception ex)
            {
                string[] row = { bioId, recipient, "FAILED" };
                var listViewItem = new ListViewItem(row);
                lvEmailStatus.Items.Add(listViewItem);
                Console.WriteLine(@"Failed sending mail " + recipient);
                return;
            }

        }

此代码工作正常,但是,应该通过datagridview中每行的每次迭代填充listview。会发生什么;它首先向datagridview中的每个人发送电子邮件,当它这样做时,程序有点冻结,但你仍然可以最小化并关闭窗口。一旦发送完成,那将是listview将填入数据的时间以及发送或失败的发送状态。但是如果我在Console.Writeline中这样做,我可以在进入datagridview的下一行之前看到发送的状态! 它应该是这样 - (选择行) - (发送电子邮件) - (参见列表视图填充) - (转到下一行) - (发送电子邮件) - (参见列表视图填充)....循环直到最后datagridview中的行。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这是因为您的方法是从UI线程调用的,但是在您的过程中您不会发布UI线程。我更喜欢使用async await来保持UI线程在繁重的过程中可用。