簡體   English   中英

C# 中基於時間的方法執行

[英]Time based Method execution in C#

我有一個方法send()我希望每 1 秒執行/調用一次。 我很難實現這一點。 到目前為止,這是我在主程序中提出的:

bool done = false;
while (!done)
{
    string vCurrent = RandomVoltage(220, 240) + "" + RandomCurrent(10, 13);
    int seconds = RandomSec();
    if (isEven(seconds))
    send(vCurrent, "169.254.156.135");//send the string to the ip address
}

所以基本上我嘗試在當前時間的每一秒調用我的send()方法,我跳過奇數秒,這是我嘗試用我的RandomSec()isEven()方法實現它的方法:

    private static readonly object syncLock = new object();
    public static int RandomSec()
    {
        lock (syncLock)
        { 
            return DateTime.Now.Second;
        }
    }

    public static bool isEven(int sec)
    {
        if ((sec % 2) == 0)
            return true;
        else return false;
    }

現在的問題是,當我在我的程序中運行 while 循環時,我的send()方法在 1 秒內發送一大串字符串,然后暫停 1 秒,然后在當前秒數再次出現時發送另一大串消息。 如何讓我的程序每 1 秒只執行一次send()方法,以便send()方法每偶數秒只發送 1 個字符串,而不是說其中的 20/30。 我可以在時間控制的循環中調用我的send()方法嗎? 任何幫助是極大的贊賞。

提前致謝。

發送一個字符串,等待/睡眠一秒鍾(或兩秒鍾)然后發送下一個字符串要容易得多。

對時間進行輪詢,每秒多次,將導致您正在體驗的效果

您可以使用計時器 class

來自上述鏈接的示例代碼:

public class Timer1
 {

     public static void Main()
     {
         System.Timers.Timer aTimer = new System.Timers.Timer();
         aTimer.Elapsed+=new ElapsedEventHandler(OnTimedEvent);
         // Set the Interval to 5 seconds.
         aTimer.Interval=5000;
         aTimer.Enabled=true;

         Console.WriteLine("Press \'q\' to quit the sample.");
         while(Console.Read()!='q');
     }

     // Specify what you want to happen when the Elapsed event is raised.
     private static void OnTimedEvent(object source, ElapsedEventArgs e)
     {
         Console.WriteLine("Hello World!");
     }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM