首页 新闻 会员 周边

.net多线程计算hash值的问题

0
悬赏园豆:10 [已关闭问题] 解决于 2012-11-16 11:44

测试环境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("-","");

    }
}
heqichang的主页 heqichang | 菜鸟二级 | 园豆:275
提问于:2012-11-16 10:48
< >
分享
其他回答(1)
0

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 方法时要考虑互斥问题。

收获园豆:5
Launcher | 园豆:45045 (高人七级) | 2012-11-16 11:10
0

楼主,最终是怎么解决的啊?

仰望星空耶 | 园豆:202 (菜鸟二级) | 2023-03-28 15:45
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册