c# - 使用套接字 tcp c# 计算发送文件的每秒速度和剩余时间

标签 c# time rate

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

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/秒)。

这是发送文件代码:

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/

相关文章:

java - 无法将日期字符串解析为日期

elasticsearch - 在Zulu日期格式上以Elasticsearch搜索文档

app-store - iOS 6 - 评分应用程序链接失效了?

php - 设置文件的日期和时间

ios - 如何检查 AVPlayer 的状态?

c++ - C++ FileApi.h没有缓存,我如何使磁盘事件达到100%

c# - 引用不经意的代码时,可空引用类型会静默失败吗?

c# - 我需要解决 Excel 猜测数据类型问题的方法

c# - 使用 PInvoke 将点 (x,y,z) 列表从 C 返回到 C#

c# - 使用应用程序池标识会导致异常和事件日志