lock vs Monitor vs Mutex之间的区别

本文详细介绍了C#中锁机制的实现方式,并对比了使用lock关键字与Monitor类的区别。通过具体的代码示例展示了如何利用Monitor类实现超时等待机制,同时提到了Mutex与Monitor的不同应用场景。

Consider this code:

lock(myGuard)
{
 // do some stuff that is being synchronized
}

the C# compiler generates the following code for you

Monitor.Enter(myGuard);
try
{
 // do some stuff that is being synchronized
}
finally
{
 Monitor.Exit(myGuard);
}

So lock is an exception proof (and short) way of acquiring a monitor and making sure it gets freed again.

but, if u use Monitor, the code blow is better.

if (!Monitor.TryEnter(obj, TimeSpan.FromSeconds(10))
{
    throw new ApplicationException("Timeout waiting for lock");
}
try
{
    ... do something with shared state ...
}
finally
{
    Monitor.Exit(obj);
}

A Mutex can be shared across processes, and is much more heavy-weight than a Monitor.

Use a Monitor unless you need to synchronize across process boundaries.

if u want to learn more, u can check

threading.rar (518.91 kb)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值