Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在do while循环中,我想执行3次特定代码,直到c中每1分钟满足一次条件#_C#_Multithreading_Timer_Do While - Fatal编程技术网

C# 在do while循环中,我想执行3次特定代码,直到c中每1分钟满足一次条件#

C# 在do while循环中,我想执行3次特定代码,直到c中每1分钟满足一次条件#,c#,multithreading,timer,do-while,C#,Multithreading,Timer,Do While,我想每1分钟执行一次函数“post mail”,直到他的标志在c#中实现3次。 基本上,当标志为false时,我想每1分钟重试函数3次 请给我解决这个问题的办法 do { isSuccess = PostMailThroughSMTP .postMail(objSmtpClient.SmtpClient, objBuildMail.MailMsg); Thread.Sleep(1000); } while (isSuccess != true);

我想每1分钟执行一次函数“post mail”,直到他的标志在c#中实现3次。 基本上,当标志为false时,我想每1分钟重试函数3次 请给我解决这个问题的办法

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

您可以使用向下计数器尝试此操作:

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

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


如果它是以多线程方式使用的,那么不要使用Thread.Sleep(x),而是使用Thread.CurrentThread.Join(x),因为这不会阻塞当前代码。

您已经更正了当前代码

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 
}
bool issucess=false;
//for比在上下文中更具可读性
for(int尝试=0;尝试<3;++尝试){
issucess=PostMailThroughSMTP.postMail(objSmtpClient.SmtpClient,objBuildMail.MailMsg);
//如果我们成功了,我们不必等一分钟
如果(isSuccess)
打破
//每分钟-60秒-60000毫秒
睡眠(60000);
}
...
如果(isSuccess){
//电子邮件已被张贴
} 
否则{
//电子邮件尚未发布
}

线程。睡眠
不是安排动作的好方法。您正在开发什么样的应用程序?Windows窗体?控制台应用程序?@TheodorZoulias控制台应用程序在这种情况下,
Thread.Sleep
正常。