lock vs Monitor vs Mutex之间的区别

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值