我如何在while循环中入睡?

问题描述 投票:0回答:1

我正在尝试每30分钟发送一封电子邮件。在while循环内。

while (true)
{
    System.Threading.Thread.Sleep(1);
    ReadInput();
    Application.DoEvents();

    MailMessage mail = new MailMessage();
    SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
    System.Threading.Thread.Sleep(2000);
    mail.From = new MailAddress("");
    mail.To.Add("");
    mail.Subject = "Test Mail";
    mail.Attachments.Add(new System.Net.Mail.Attachment("C://Users//matte//test.txt"));
    mail.Body = "This is for testing SMTP mail from GMAIL";

    SmtpServer.Port = 587;
    SmtpServer.Credentials = new System.Net.NetworkCredential("", "");
    SmtpServer.EnableSsl = true;
    SmtpServer.Send(mail);
    System.Threading.Thread.Sleep(10000);
}

我尝试进行冷却,但是电子邮件一直不停地发送。我怎样才能做到这一点。这样每30分钟发送一次电子邮件?

c# email error-handling gmail sleep
1个回答
2
投票

Sleep函数以毫秒为单位接收大量时间,因此它现在正在等待。

public static void Sleep (int millisecondsTimeout);

无论如何,睡眠都不是您可以使用的最佳选择,因为它会阻止正在运行的进程。我将在发送电子邮件时使用日期时间,并将System.DateTime.Now与该值进行比较,因此程序将继续响应,您可以等待,仅检查两个日期时间之间的时差是否足够。

DateTime LastSend = System.DateTime.Now;
While (true)
{
    if (LastSend.AddMinutes(30) > System.DateTime.Now)
        continue;
    ... your process ...
    LastSend = System.DateTime.Now;
}

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.