C#语法锁 - 2个问题 [英] C# Lock syntax - 2 questions

查看:128
本文介绍了C#语法锁 - 2个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用字符串作为更衣室的锁?

 锁(东西)
 

我可以做无锁牙套如果只有一条线?

 锁(东西)富();
 

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆