C # execution method in another thread

I have a method that reads some files and gets SHA1Managed hashes and then compares it with other hashes from the list, how can I make this method in another thread?

public bool CheckFile(string file, string filehash) { if (File.Exists(file)) { using (FileStream stream = File.OpenRead(file)) { SHA1Managed sha = new SHA1Managed(); byte[] checksum = sha.ComputeHash(stream); string sendCheckSum = BitConverter.ToString(checksum) .Replace("-", string.Empty); return sendCheckSum.ToLower() == filehash; } } else return false; } 
+5
source share
2 answers

If you just want to run it in the background thread, you really need to move the task creation one level, since your function will return the result. Depending on how the calling code works, something like this might work for you.

 var backgroundTask = Task.Factory.StartNew(() => { var result = CheckFile("file", "filehash"); //do something with the result }); 
+4
source

Try these codes:

 public async Task<bool> CheckFile(string file, string filehash) { await Task.Run<bool>(()=> { if (File.Exists(file)) { using (FileStream stream = File.OpenRead(file)) { SHA1Managed sha = new SHA1Managed(); byte[] checksum = sha.ComputeHash(stream); string sendCheckSum = BitConverter.ToString(checksum) .Replace("-", string.Empty); return sendCheckSum.ToLower() == filehash; } } else return false; }); } 
0
source

All Articles