【问题标题】:Inside do while loop, I want to execute specific code for 3 times till condition satisfy for every 1 min in c#在 do while 循环内部,我想在 c# 中每 1 分钟执行一次特定代码,直到条件满足
【发布时间】:2020-02-07 18:30:23
【问题描述】:

我想每 1 分钟执行一次“发布邮件”功能,直到他的标志仅在 c# 中 3 次为真。 基本上,当标志为假时,我想每 1 分钟重试 3 次函数 请给我解决方案

do
{
    isSuccess = PostMailThroughSMTP
                .postMail(objSmtpClient.SmtpClient, objBuildMail.MailMsg);
    Thread.Sleep(1000);
}
while (isSuccess != true);

【问题讨论】:

  • Thread.Sleep 不是安排操作的好方法。您正在开发什么样的应用程序? Windows 窗体?控制台应用程序?
  • @TheodorZoulias 控制台应用
  • 在这种情况下Thread.Sleep 是可以的。

标签: c# multithreading timer do-while


【解决方案1】:

您可以使用递减计数器试试这个:

int count = 3;
do
{
  isSuccess = PostMailThroughSMTP
              .postMail(objSmtpClient.SmtpClient, objBuildMail.MailMsg);
  Thread.Sleep(1000);
}
while ( isSuccess != true && --count >= 1 );

【讨论】:

    【解决方案2】:

    计时器是一种在间隔上执行功能的方法,比如说每分钟。在 Elapsed 事件中,您可以放置​​一个带有 for 循环的方法,该循环在 isSuccess 为 true 时执行 PostMailThroughSMTP 三次或更少。

    如果它以多线程方式使用,则不要使用 Thread.Sleep(x) 而是使用 Thread.CurrentThread.Join(x) 因为那不是阻塞。

    【讨论】:

      【解决方案3】:

      您当前的代码已更正

      bool isSuccess = false;
      
      // for is more readable than while in the context
      for (int attempt = 0; attempt < 3; ++attempt) {
        isSuccess = PostMailThroughSMTP.postMail(objSmtpClient.SmtpClient, objBuildMail.MailMsg); 
      
        // If we succeeded, we don't have to wait a minute
        if (isSuccess)
          break;
      
        // Every minute - 60 seconds - 60000 milliseconds
        Thread.Sleep(60000);  
      }
      
      ...
      
      if (isSuccess) {
        // eMail has been posted
      } 
      else {
        // eMail has NOT been posted 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-16
        • 2012-04-21
        • 1970-01-01
        • 2018-11-09
        相关资源
        最近更新 更多