private object lockObj = new object();
private Dictionary<int, string> dict = new Dictionary<int, string>();
public string GetOrAddFromDict(int key)
{
string value;
// non-locked access:
if (dict.TryGetValue(key, out value))
return value;
lock (this.lockObj)
{
if (dict.TryGetValue(key, out value))
return value;
string newValue = "value of " + key; // place long operation here
dict.Add(key, newValue);
return newValue;
}
}
Run Code Online (Sandbox Code Playgroud)
问题a:它是否是线程安全的?如果是,为什么?
问题b:这个双TryGetValue()模式是如何调用的?
有人可以解释以下System.Numerics.BigInteger行为吗?
Console.WriteLine(Math.Log10(100)); // prints 2
Console.WriteLine(Math.Log10(1000)); // prints 3 (as expected)
Console.WriteLine((int)Math.Log10(100)); // prints 2
Console.WriteLine((int)Math.Log10(1000)); // prints 3 (as axpected)
var bi100 = new BigInteger(100);
var bi1000 = new BigInteger(1000);
Console.WriteLine(BigInteger.Log10(bi100)); // prints 2
Console.WriteLine(BigInteger.Log10(bi1000)); // prints 3 (as axpected)
Console.WriteLine((int)BigInteger.Log10(bi100)); // prints 2
Console.WriteLine((int)BigInteger.Log10(bi1000)); // prints 2 ???????
Console.WriteLine(Math.Floor(BigInteger.Log10(bi100))); // prints 2
Console.WriteLine(Math.Floor(BigInteger.Log10(bi1000))); // prints 2 ???????
Console.WriteLine(Math.Round(BigInteger.Log10(bi100))); // prints 2
Console.WriteLine(Math.Round(BigInteger.Log10(bi1000))); // prints 3 (as expected)
Run Code Online (Sandbox Code Playgroud)
编辑:请注意,我知道这是一个问题.我想知道为什么 Math.Log10和BigInteger.Log10的行为有所不同.