【发布时间】:2015-01-23 20:44:20
【问题描述】:
我有以下方法:
public static string Sha256Hash(string input) {
if(String.IsNullOrEmpty(input)) return String.Empty;
using(HashAlgorithm algorithm = new SHA256CryptoServiceProvider()) {
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = algorithm.ComputeHash(inputBytes);
return BitConverter.ToString(hashBytes).Replace("-", String.Empty);
}
}
有没有办法让它异步?我希望使用 async 和 await 关键字,但 HashAlgorithm 类不为此提供任何异步支持。
另一种方法是将所有逻辑封装在一个:
public static async string Sha256Hash(string input) {
return await Task.Run(() => {
//Hashing here...
});
}
但这似乎并不干净,我不确定它是否是异步执行操作的正确(或有效)方式。
我该怎么做才能做到这一点?
【问题讨论】:
-
您为什么要尝试异步执行此操作?
-
@CoryNelson 老实说,我不知道。我认为我会通过使其异步运行或在另一个线程上运行来优化代码。但答案让我清醒了。
-
@CoryNelson:我最近遇到了一种情况,我需要异步执行此操作,以便在计算大文件的哈希值时保持响应式 UI。
标签: c# .net asynchronous async-await sha256