C#语法锁 - 2个问题 [英] C# Lock syntax - 2 questions
问题描述
我可以使用字符串作为更衣室的锁?
锁(东西)
我可以做无锁牙套如果只有一条线?
锁(东西)富();
1)是的,字符串(一般)拘留(默认,感谢@Eric),同样的,所以任何实例东西
将指向同一个对象,所以你会好起来。 这是的非常的做法不好,但因为其他人,在另一个库,比如可以锁定您的字符串,从而使死锁的可能性在这里看到:<一href="http://stackoverflow.com/questions/4192969/using-string-as-a-lock-to-do-thread-synchronization">Using字符串作为一个锁来做线程同步
您应该这样做:
私有静态只读对象互斥=新的对象();
锁(互斥)
{
// ....
}
2)是的,同所有语句。 *什么,你有:
{
// 一条线
}
可能仅仅是
//一号线
*几乎所有的东西,看到了@ 抓
块,这需要大括号的LukeH的例子。
Can I use string as locker in the Lock ?
lock("something")
Can I do lock without braces if its only one line ?
lock("something") foo();
1) Yes, strings are (generally) interned (by default, thanks @Eric), so any instance of the same "something"
would point to the same object, therefore you'd be ok. This is very bad practice though, because someone else, in another library for example, could lock on your string, thus giving the potential for deadlocks. See here: Using string as a lock to do thread synchronization
You should do this:
private static readonly object mutex = new object();
lock(mutex)
{
//....
}
2) Yes, same with all statements. Anything* where you have:
{
// One line
}
could just be
// One line
*Almost anything, see @LukeH's example of the catch
block, which requires the braces.
这篇关于C#语法锁 - 2个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!