15.12 The lock statementreleases the lock.

本文详细介绍了C#中锁(lock)语句的使用方法及原理,解释了如何通过lock语句实现线程间的互斥访问,并举例说明了在静态方法中使用类的System.Type对象作为锁的便利性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

lock ( expression ) embedded-statement
The expression of a lock statement must denote a value of a reference-type.
No implicit boxing conversion
(§13.1.5) is ever performed for the expression of a lock statement, and
thus it is a compile-time error for the
expression to denote a value of a value-type.
A lock statement of the form
lock (x) .
where x is an expression of a reference-type, is precisely equivalent to
System.Threading.Monitor.Enter(x);
try {
.
}
finally {
System.Threading.Monitor.Exit(x);
}
except that x is only evaluated once.
[Example: The System.Type object of a class can conveniently be used as the
mutual-exclusion lock for
static methods of the class. For example:
class Cache
{
public static void Add(object x) {
lock (typeof(Cache)) {
.
}
}
public static void Remove(object x) {
lock (typeof(Cache)) {
.
}
}
}
end example]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值