我有一个程序可以一次从几 (3) 个线程以高速率将文件写入网络共享。
运行一段时间(通常是一小段时间)后,其中一些线程会卡住。使用 Process Monitor,我可以看到对 WriteFile 和 CloseFile 的调用根本没有答案。
此时,我根本无法关闭该进程,即使从任务管理器中将其杀死也无济于事。
有趣的是,当托管共享的计算机运行 Windows Server 2008 (R2) 时,就会发生这种情况。如果我将共享移动到 Windows 2003 计算机,我看不到这些问题。此外,如果程序在运行 Windows Server 2008 的计算机(与共享主机不同的计算机)上运行,我只会看到此问题。
这是一个快速重现问题的简短程序。源目录中的文件大小范围为 1 到 20 MB:
Imports System.IO
Imports System.Threading
Module Module1
Private m_sourceFiles As FileInfo()
Private m_targetDir As String
Sub Main(ByVal args As String())
Dim sourceDir As New DirectoryInfo(args(0))
m_sourceFiles = sourceDir.GetFiles()
m_targetDir = args(1)
For i As Integer = 0 To 2
ThreadPool.QueueUserWorkItem(AddressOf DoWork)
Next
Console.ReadLine()
End Sub
Private Const BUFFER_SIZE As Integer = (128 * 1024)
Private Sub DoWork(ByVal o As Object)
Console.WriteLine(Thread.CurrentThread.ManagedThreadId)
Dim random As New Random(Thread.CurrentThread.ManagedThreadId)
While True
Dim fileIndex As Integer = random.Next(m_sourceFiles.Count)
Dim sourceFile As FileInfo = m_sourceFiles(fileIndex)
Dim input As FileStream = sourceFile.OpenRead
Dim targetName As String = sourceFile.Name.Replace(sourceFile.Extension, random.Next(Integer.MaxValue) & sourceFile.Extension)
Dim targetPath As String = m_targetDir & "\" & targetName
Dim output As FileStream = File.Create(targetPath)
Dim bytes() As Byte = New Byte((BUFFER_SIZE) - 1) {}
Dim read As Integer = input.Read(bytes, 0, bytes.Length)
While read <> 0
output.Write(bytes, 0, read)
read = input.Read(bytes, 0, bytes.Length)
End While
output.Flush()
output.Close()
Console.WriteLine(Thread.CurrentThread.ManagedThreadId & " - " & targetName)
End While
End Sub
End Module