C#在其他线程上执行方法(C# execute method on other thread)
我有一个方法读取一些文件并获得散列SHA1Managed,然后将其与列表中的其他散列进行比较,如何在其他线程上执行此方法?
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; }i have a method that read some files and get hashes SHA1Managed and then compare it with other hashes from a list, how can i do this method on other 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; }最满意答案
如果你只是想在后台线程中运行它,你实际上需要将任务创建从一个级别上移到一个级别,因为你的函数返回一个结果。 根据调用代码的工作原理,这可能适用于您。
var backgroundTask = Task.Factory.StartNew(() => { var result = CheckFile("file", "filehash"); //do something with the result });If you just want to run it in a background thread you'd actually need to move the task creation up one level since your function returns a 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 });更多推荐
发布评论