How to run a thread until a condition becomes true in c#

后端 未结 2 641
孤街浪徒
孤街浪徒 2021-01-29 15:27

I am writing a program to send SMS every 5 minutes. I want to stop this when the system time is 6 PM. How can I do that? This is my current code. I want to modify this accordin

2条回答
  •  被撕碎了的回忆
    2021-01-29 16:25

    Generally never use Sleep is bad idea , use timer instead:

    System.Timers.Timer SendSMS = new System.Timers.Timer();        
    SendSMS.Interval = 300000;  ///300000ms=5min    
    SendSMS.Elapsed += new System.Timers.ElapsedEventHandler(SendSMS_Elapsed);
    SendSMS.Enabled=true;
    
     void SendSMS_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                sms.SendSMS();
            }     
    

    Add a second timer to check the time and stop when is 6pm:

     System.Timers.Timer StopSendSMS = new System.Timers.Timer();        
        StopSendSMS.Interval = 100;      
        StopSendSMS.Elapsed += new System.Timers.ElapsedEventHandler( StopSendSMS_Elapsed);
        StopSendSMS.Enabled=true;
    
    
     void StopSendSMS_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
                {
                      if (int(DateTime.Now.Hour)==18))
                       {
                         SendSMS.Enabled=false;
                         StopSendSMS.Enabled=false; ///no need to check anymore
                       }
    
                }   
    

提交回复
热议问题