C#在其他线程上执行方法(C# execute method on other thread)

编程入门 行业动态 更新时间:2024-10-18 03:30:15
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 });

更多推荐

本文发布于:2023-08-07 13:31:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   方法   execute   method   thread

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!