簡體   English   中英

C#等待或暫停下一行之前的X秒

[英]C# WaitFor or Pause for X Seconds Before Next Line

我正在試圖弄清楚應該是最好的方法來做到以下幾點? 我有一個與httpwebrequest一起使用的控制台應用程序。 在我的應用程序的某些部分,我想這樣做:

  agent.GetURL("http://site.com/etc.../"); 
Wait for 8-16 Seconds<-Should be random  
 Agent.GetURL("http://site.com/etc.../");
Wait for 4-6 Seconds etc...

請求是時間敏感的,因此計算機時間應該與每個請求不同,我不能請求等待它完成並再次請求。 我讀過有關計時器的信息,thread.sleep。 我擔心我沒有停止或暫停的經驗不想在將來遇到問題。 那么如果你能告訴我這種代碼的最佳方法是什么?

並且timer / thread.sleep是否可以在函數內部並在需要時使用它?

謝謝!

編輯:這個程序是隱形的,所以我需要一個解決方案,加載圓圈鼠標:)

嘗試

Random random = new Random();
int timeDelay = random.Next(8, 16);

Thread.Sleep(timeDelay * 1000); //time in milliseconds

這個問題提供了一種在定義的范圍內生成隨機數的方法,您可以將其原樣並將其包裝在另一種方法中以暫停一段隨機秒。

代碼可能如下所示:

// Method from the linked answer, copy-pasted here for completeness
// added the relevant fields because the original code is an override
public Int32 GetNewRandomNumber(Int32 minValue, Int32 maxValue)
{
    RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
    byte[] _uInt32Buffer = new byte[4];

    if (minValue > maxValue) 
        throw new ArgumentOutOfRangeException("minValue");
    if (minValue == maxValue) return minValue;
    Int64 diff = maxValue - minValue;
    while (true)
    {
        _rng.GetBytes(_uint32Buffer);
        UInt32 rand = BitConverter.ToUInt32(_uint32Buffer, 0);

        Int64 max = (1 + (Int64)UInt32.MaxValue);
        Int64 remainder = max % diff;
        if (rand < max - remainder)
        {
            return (Int32)(minValue + (rand % diff));
        }
    }
}

public void RandomWait(int minWait, int maxWait)
{
    // Thread.Sleep() wants a number of milliseconds to wait
    // We're going, as an example, to wait between 8 and 16 seconds
    System.Threading.Thread.Sleep(GetNewRandomNumber(8, 16) * 1000);
}

然后你只需在需要時調用RandomWait()

使用Thread.Sleep(miliseconds)停止執行所需的時間。

暫無
暫無

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

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