From f93548855c0605ca2a258a87d4ac9cb02df18135 Mon Sep 17 00:00:00 2001 From: Jan Sandbrink Date: Fri, 27 Dec 2013 10:34:25 +0100 Subject: [PATCH] minimal parallelism --- CompareFS/PathComparator.cs | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/CompareFS/PathComparator.cs b/CompareFS/PathComparator.cs index 4d56dda..f96c19b 100644 --- a/CompareFS/PathComparator.cs +++ b/CompareFS/PathComparator.cs @@ -4,6 +4,7 @@ using System.Text; using System.IO; using System.Security.Cryptography; +using System.Threading.Tasks; namespace CompareFS { @@ -60,7 +61,7 @@ private void CompareFiles(DirectoryInfo referenceDirectory, DirectoryInfo target { foreach (Pair pair in EnumerateCommonFilesLeftAndRight(targetDirectory, referenceDirectory)) { - if (!CompareFiles(pair.Left, pair.Right)) + if (!CompareFilesAsync(pair.Left, pair.Right).Result) { Listener.OnModification(new FileModification(pair.Left, ModificationType.Changed)); } @@ -78,16 +79,24 @@ private IEnumerable> EnumerateCommonFilesLeftAndRight(DirectoryIn return leftFiles.EnumerateFiles().Where(f => !ExcludedFileExtensions.Contains(f.Extension)).Where(f => rightFiles.HasFile(f)).Select(left => new Pair(left, rightFiles.GetCorrespondingFile(left))); } - private bool CompareFiles(FileInfo fileInfo1, FileInfo fileInfo2) + private async Task CompareFilesAsync(FileInfo fileInfo1, FileInfo fileInfo2) { - SHA1 hashAlgorithm = SHA1.Create(); + using (var stream1 = fileInfo1.OpenRead()) using (var stream2 = fileInfo2.OpenRead()) { - byte[] hash1 = hashAlgorithm.ComputeHash(stream1); - byte[] hash2 = hashAlgorithm.ComputeHash(stream2); + Task hash1 = ComputeHashAsync(stream1); + Task hash2 = ComputeHashAsync(stream2); - return ByteArrayCompare(hash1, hash2); + return ByteArrayCompare(await hash1, await hash2); + } + } + + private async Task ComputeHashAsync(Stream source) + { + using (SHA1 hashAlgorithm = SHA1.Create()) + { + return await Task.Factory.StartNew(() => hashAlgorithm.ComputeHash(source)); } }