如何计算每秒的速度以及以秒为单位的剩余时间?我尝试使用:

void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
    long prevSum = 0;
    while (fileTransfer.busy) {
        rate = (fileTransfer.sum - prevSum);
        RateLabel(rate);  //converting prevSum to (int)KB/SEC
        if (rate != 0)
            left = (fileTransfer.fileSize - fileTransfer.sum) / rate;
        TimeSpan t = TimeSpan.FromSeconds(left);
        timeLeftLabel(FormatRemainingText(rate, t)); //show how much left
        prevSum = fileTransfer.sum;
        Thread.Sleep(1000);
    }
}


但速率和剩余时间会永久性地上下波动(分别为30MB /秒和5MB /秒)。

这是sendfile代码:

public static void sendFile(string filePath) {
    // run the progres Form
    Thread thFP = new Thread(fpRUN);
    fileProgress fP = new fileProgress("Sending...");
    thFP.Start(fP);

    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    string fileName = Path.GetFileName(filePath);
    byte[] fileData;
    try {
        //sending file name and file size to the server
        busy = true;
        fileSize = fs.Length;
        byte[] fileDetial = null;
        string detail =  fileName + "," + fileSize.ToString();
        fileDetial = Encoding.ASCII.GetBytes(detail);
        client.Send(fileDetial);

        //sending file data to the server
        fileData = new byte[packetSize];
        count = 0;
        sum = 0;

        fP.SizeLabel(fileSize); // tell the form the file size
        while (sum < fileSize) {
            fs.Seek(sum, SeekOrigin.Begin);
            fs.Read(fileData, 0, fileData.Length);
            count = client.Send(fileData, 0, fileData.Length, SocketFlags.None);
            sum += count;
            fP.ProgressBarFileHandler(sum,fileSize); //progressbar value
            fP.SentLabel(sum);                  //tell the form how much sent
        }
    }
    finally {
        busy = false;
        fs.Close();
        fileData = null;
        MessageBox.Show(string.Format("{0} sent successfully", fileName));
    }
}


我该如何解决?有没有更好的方法来计算速度?

最佳答案

您可以对传输速度进行一些平滑处理,以避免值跳变。有关一个选项,请参见http://en.wikipedia.org/wiki/Moving_average。基本上计算一段时间内速度的某种平均值。

关于c# - 计算每秒速度和使用套接字TCP C#发送文件的剩余时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9029218/

10-15 17:15