How can I rate limit an upload using TcpClient?

后端 未结 4 1243
刺人心
刺人心 2021-01-06 18:23

I\'m writing a utility that will be uploading a bunch of files, and would like to provide the option to rate limit uploads. What is the best approach for rate limiting uploa

4条回答
  •  隐瞒了意图╮
    2021-01-06 18:41

    Implementing speed limit is relatively easy, take a look at the following snippet:

    const int OneSecond = 1000;
    
    int SpeedLimit = 1024; // Speed limit 1kib/s
    
    int Transmitted = 0;
    Stopwatch Watch = new Stopwatch();
    Watch.Start();
    while(...)
    {
        // Your send logic, which return BytesTransmitted
        Transmitted += BytesTransmitted;
    
        // Check moment speed every five second, you can choose any value
        int Elapsed = (int)Watch.ElapsedMilliseconds;
        if (Elapsed > 5000)
        {
            int ExpectedTransmit = SpeedLimit * Elapsed / OneSecond;
            int TransmitDelta = Transmitted - ExpectedTransmit;
            // Speed limit exceeded, put thread into sleep
            if (TransmitDelta > 0)
                Thread.Wait(TransmitDelta * OneSecond / SpeedLimit);
    
            Transmitted = 0;
            Watch.Reset();
        }
    }
    Watch.Stop();
    

    This is draft untested code, but I think it is enough to get the main idea.

提交回复
热议问题