KeyedHashAlgorithm.ComputeHash()同じ に対して非決定論的な結果が得られるため、それはスレッドセーフではないことを知っておく価値がありますKeyedHashAlgorithm.Key。
私の場合、KeyedHashAlgorithm をキャッシュしたいのは、クライアント側からの信頼性KeyedHashAlgorithm.Keyを検証するために常に同じであるためです。おそらく、内部変数をインスタンスにキャッシュします。スレッドごとにインスタンスをキャッシュする必要があります。これはテストです:ComputeHash()KeyedHashAlgorithmThreadStaticThreadLocal
静的KeyedHashAlgorithmは一貫性のない結果をもたらします:
var kha = KeyedHashAlgorithm.Create("HMACSHA256");
kha.Key = Encoding.UTF8.GetBytes("key");
Action comp = () =>
{
var computed = kha.ComputeHash(Encoding.UTF8.GetBytes("message"));
Console.WriteLine(Convert.ToBase64String(computed));
};
Parallel.Invoke(comp, comp, comp, comp, comp, comp, comp, comp);
KeyedHashAlgorithmスレッドごとの比較:
ThreadLocal<KeyedHashAlgorithm> tl= new ThreadLocal<KeyedHashAlgorithm>(() =>
{
var kha = KeyedHashAlgorithm.Create("HMACSHA256");
kha.Key = Encoding.UTF8.GetBytes("key");
return kha;
});
Action comp = () =>
{
var computed = tl.Value.ComputeHash(Encoding.UTF8.GetBytes("message"));
Console.WriteLine(Convert.ToBase64String(computed));
};
Parallel.Invoke(comp, comp, comp, comp, comp, comp, comp, comp);
このコードは、「スレッド セーフ」の結果について他の関数をテストするために使用できます。これが他の人に役立つことを願っています。