异步SHA256哈希 [英] Asynchronous SHA256 Hashing

查看:114
本文介绍了异步SHA256哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

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类对此不提供任何异步支持.

Is there a way to make it asynchronous? I was hoping to use the async and await keywords, but the HashAlgorithm class does not provide any asynchronous support for this.

另一种方法是将所有逻辑封装在一个中:

Another approach was to encapsulate all the logic in a:

public static async string Sha256Hash(string input) {
     return await Task.Run(() => {
         //Hashing here...
     });
}

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

But this does not seem clean and I'm not sure if it's a correct (or efficient) way to perform an operation asynchronously.

我该怎么做?

推荐答案

您正在做的工作本质上是同步CPU绑定的工作.它并不是天生就异步的,就像网络IO一样.如果您想在另一个线程中运行一些同步CPU绑定的工作并异步地等待它完成,那么<​​c1>确实是完成此任务的合适工具,假设该操作运行了很长时间,需要异步执行.

The work that you're doing is inherently synchronous CPU bound work. It's not inherently asynchronous as something like network IO is going to be. If you would like to run some synchronous CPU bound work in another thread and asynchronously wait for it to be completed, then Task.Run is indeed the proper tool to accomplish that, assuming the operation is sufficiently long running to need to perform it asynchronously.

说,确实没有任何原因在同步方法上公开异步包装器.通常,仅公开同步方法更有意义,如果特定调用者需要它在另一个线程中异步运行,则他们可以使用Task.Run显式指示需要特定的调用.

That said, there really isn't any reason to expose an asynchronous wrapper over your synchronous method. It generally makes more sense to just expose the method synchronously, and if a particular caller needs it to run asynchronously in another thread, they can use Task.Run to explicitly indicate that need for that particular invocation.

这篇关于异步SHA256哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆