我想并行计算文件的几个不同散列,以提高应用程序的性能。
我有以下代码:
Dim lThreads As List(Of Thread) = New List(Of Thread)()
For i = 0 To algorithms.Count - 1
Dim index = i
Dim t As Thread = New Thread(
New ThreadStart(Sub()
Dim reader2 as System.IO.FileStream = reader
reader2.position = 0
listDigestvalue(index) = CalculateHash(algorithm, listReader(index))
End Sub))
t.Name = "Thread of algorithm: " + shortnameofalgorithm
t.Start()
lThreads.Add(t)
Next
For i = 0 To lThreads.Count - 1
lThreads(i).Join()
Next
问题是,对于每次执行,程序都不会生成文件的正确哈希值。
还有另一种方法可以并行化这些操作。
谢谢你。
感谢@jmcilhinney,我终于用这段代码解决了我的问题。
Dim reader = New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, hashBufferSize)
Dim bytesFile() As Byte = GetStreamAsByteArray(reader)
Dim lTasks As List(Of Task) = New List(Of Task)()
For i = 0 To algorithms.Count - 1
Dim index = i
Dim shortnameofalgorithm = algorithms(i).shortname
Dim t As Task = Task.Run(Sub()
listDigestvalue(index) = CalculateHash(shortnameofalgorithm, bytesFile)
End Sub)
lTasks.Add(t)
Next
Task.WaitAll(lTasks.ToArray)
For j = 0 To lTasks.Count - 1
algorithms(j).hashValue = listDigestvalue(j)
Next
可以对线程进行同样的操作,但是我选择“任务”是因为它可以提高应用程序的性能。
非常感谢。