加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 异步SHA256哈希

发布时间:2020-12-15 18:30:01 所属栏目:百科 来源:网络整理
导读:我有以下方法: public static string Sha256Hash(string input) { if(String.IsNullOrEmpty(input)) return String.Empty; using(HashAlgorithm algorithm = new SHA256CryptoServiceProvider()) { byte[] inputBytes = Encoding.UTF8.GetBytes(input); byt
我有以下方法:
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...
     });
}

但这似乎并不干净,我不确定它是否是一种异步执行操作的正确(或有效)方式.

我该怎么做才能做到这一点?

解决方法

您正在进行的工作本质上是同步CPU绑定工作.它本身并不是异步的,就像网络IO一样.如果你想在另一个线程中运行一些同步CPU绑定工作并异步等待它完成,那么Task.Run确实是完成它的正确工具,假设操作足够长,需要异步执行它.

That said,there really isn’t any reason to expose an asynchronous wrapper over your synchronous method.通常同步公开方法更有意义,如果特定调用者需要它在另一个线程中异步运行,他们可以使用Task.Run明确指出对该特定调用的需要.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读