问题描述:

I have the following method:

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);

}

}

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.

What can I do to accomplish this?

网友答案:

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.

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.

网友答案:

The overhead of running this asynchronously (using Task.Run) will probably be higher that just running it synchronously.

An asynchronous interface is not available because it is a CPU bound operation. You can make it asynchronous (using Task.Run) as you pointed out, but I would recommend against it.

相关阅读:
Top