例如,鉴于 Collection 不是威胁安全的:
var myDic = new Dictionary<string, string>();
在多线程环境中,这将抛出:
string s = null;
if (!myDic.TryGetValue("keyName", out s)) {
s = new string('#', 10);
myDic.Add("keyName", s);
}
当一个线程试图将 KeyValuePair 添加到字典 myDic 中时,另一个线程可能会 TryGetValue()。由于Collection不能同时读写,会出现Exception。
但是,另一方面,如果您尝试以下操作:
// Other threads will wait here until the variable myDic gets unlocked from the preceding thread that has locked it.
lock (myDic) {
string s = null;
if (!myDic.TryGetValue("keyName", out s)) {
s = new string('#', 10);
myDic.Add("keyName", s);
}
} // The first thread that locked the myDic variable will now release the lock so that other threads will be able to work with the variable.
然后突然之间,第二个线程试图获得相同的“keyName”键值将不必将它添加到字典中,因为第一个线程已经添加了它。
所以简而言之,线程安全意味着一个对象支持同时被多个线程使用,或者会为你适当地锁定线程,而不必担心线程安全。
2.我不认为 GhostScript 现在是线程安全的。它主要使用多个线程来执行其任务,因此这使其提供了更高的性能,仅此而已。
3.根据您的预算和要求,这可能是值得的。但是如果你围绕包装器构建,你可能只能在方便的地方使用 lock() ,或者如果你自己不使用多线程,那么绝对不值得为线程安全付费。这仅意味着如果您的应用程序使用多线程,那么您将不会遭受库不是线程安全的后果。除非你真的多线程,否则不值得为线程安全库付费。