測試環境vs2010 + .net 4.0 下面這段代碼經常報:“已關閉 Safe handle”或者“哈希不適于在指定狀態下使用”錯誤,請問下是什么原因造成的?class Program{ static void Main(string[] args) { Parallel.For(0, 100, n => { Console.WriteLine(SetMd5("test")); }); } private static HashAlgorithm hash = MD5.Create(); public static String SetMd5(String text) { //HashAlgorithm hash = MD5.Create(); Byte[] bytes = hash.ComputeHash(Encoding.UTF8.GetBytes(text)); return BitConverter.ToString(bytes).Replace("-",""); }}
2 回答

茅侃侃
TA貢獻1842條經驗 獲得超21個贊
Parallel.For(0, 100, n =>
{
HashAlgorithm hash = MD5.Create();
Byte[] bytes = hash.ComputeHash(Encoding.UTF8.GetBytes("test"));
Console.WriteLine(BitConverter.ToString(bytes).Replace("-",""));
});
如果你這么寫沒有出錯的話,那么可以斷定 HashAlgorithm 的 ComputeHash 不是線程安全的。因此你的代碼在調用同一個
HashAlgorithm 實例的 ComputeHash 方法時要考慮互斥問題。
- 2 回答
- 0 關注
- 715 瀏覽
添加回答
舉報
0/150
提交
取消