对于需要在后台运行的大型文件,我需要一个SHA256哈希函数。我想有可能取消执行(我认为带有CancellationToken)。使用库功能时,我没有找到根据要求取消该过程的方法。
private byte[] SHA256_Hash(string fileName) {
byte[] result = null;
using (SHA256 sha256 = SHA256.Create()) {
int bufferSize = 10 * 1024 * 1024; // 10MB
using (var stream = new BufferedStream(File.OpenRead(fileName), bufferSize)) {
result = sha256.ComputeHash(stream);
}
}
return result;
}
例如,您可以尝试取消流阅读(stream.ReadAsync
)
private static async Task<byte[]> SHA256_HashAsync(string fileName,
CancellationToken token) {
using (SHA256 sha256 = SHA256.Create()) {
// we are going to read large file block after block
// each read can be cancelled
var buffer = new byte[8 * 1024]; // <- typical 8k bytes block
using (var stream = new BufferedStream(File.OpenRead(fileName), buffer.Length)) {
int read = 0;
// read next block...
while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, token)) != 0)
sha256.TransformBlock(buffer, 0, read, buffer, 0); //... add it ti SHA
// final (may be incomplete) block
sha256.TransformFinalBlock(buffer, 0, read);
return sha256.Hash;
}
}
}
可能的用法
using (CancellationTokenSource src = new CancellationTokenSource(5000)) {
try {
byte[] hash = await SHA256_HashAsync(@"c:\MyLongFile.dat", src.Token);
// relevant code here
}
catch (TaskCanceledException) {
// 5 seconds is not enough to compute SHA256 hash
}
}