加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 00:05:08 所属栏目:百科 来源:网络整理
导读:我正在试图弄清楚应该是最好的方法来做到以下几点? 我有一个与httpwebrequest一起使用的控制台应用程序. 在我的应用程序的某些部分,我想这样做: agent.GetURL("http://site.com/etc.../"); Wait for 8-16 Seconds-Should be random Agent.GetURL("http://s
我正在试图弄清楚应该是最好的方法来做到以下几点?
我有一个与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是否可以在函数内部并在需要时使用它?

谢谢!

编辑:这个程序是隐形的,所以我需要一个解决方案,加载圆圈鼠标:)

解决方法

This question提供了一种在定义的范围内生成随机数的方法,您可以将其原样并将其包装在另一种方法中以暂停一段随机秒.

代码可能如下所示:

// 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().

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读