首页 > 解决方案 > 为什么使用 Filestream 复制文件移动很快,然后在完成之前有很长的延迟?

问题描述

我正在使用一对 io.filestreams 来复制文件,因此我可以在复制文件时监控文件的进度。但是,与系统副本相比,副本率似乎很奇怪。该文件正在从本地机器复制到远程机器(使用 UNC 路径),并且无论机器如何,它看起来都是一致的。

作为参考,如果通过拖放文件复制文件,大约需要 13 秒,windows 文件复制进度条会相应反映这一点。

如果我用我的代码复制文件,“进度条”显示所有字节都在一秒钟内被复制,然后在执行读取的文件流关闭时大约有 12 秒的延迟。

我曾尝试在写作过程中刷新流,但这似乎没有任何影响。为什么字节显示写得如此之快,然后在代码退出 Filestream Using 循环时发生延迟?

这是我正在使用的方法:

Public Sub CopyFileInByteChunks(SourcePathFile As String, DestinationPathFile As String, NumberOf1KByteChunks As Long)

    Dim CopyBufferSize As Long = 1024 * 1024

    Console.WriteLine("START")
    Using sr = New IO.FileStream(SourcePathFile, IO.FileMode.Open, FileAccess.Read)
        Using sw = New IO.FileStream(DestinationPathFile, IO.FileMode.Create)
            Dim ThisFileBytesSoFar As Long = 0
            sw.SetLength(sr.Length) 'Ensures that the write out will be in contiguous bytes on the device (disk)
            Dim byteData(CopyBufferSize) As Byte
            Dim bytesRead As Long
            Do
                bytesRead = sr.Read(byteData, 0, CopyBufferSize) 'read 1 buffer worth of data
                ThisFileBytesSoFar += bytesRead 'for prog bar
                sw.Write(byteData, 0, bytesRead)
                Console.WriteLine(ThisFileBytesSoFar)
                If bytesRead = 0 Then
                    Exit Do
                End If
            Loop
            Console.WriteLine("Completed Copy Loop")
        End Using
        Console.WriteLine("Exited Writer Using")
    End Using
    Console.WriteLine("Exited Reader Using")
End Sub

标签: vb.netfilefilestream

解决方案


推荐阅读