On May 15, 6:01*am, "Tony Johansson" <johansson.anders...@telia.com>
wrote:
> Hi!
>
> If I want to lock a section in the code from concurrency item problems I can
> use the static Monitor class in this way
> Monitor:Enter
> ...
> Monitor.Exit
>
> I can also use the C# lock keyword to lock the same section.
>
> So I don't see any point at all to use the Monitor.Enter... Monitor.Exit
> instead of the lock keword just to lock a section in the code because of two
> reasons.
> 1. It much less to write lock then the other
> 2. The most importand it that you get the try..finally for free which mean
> that you will always
> free the lock in case of running into same kind of exception
>
> Is this correct understood ?
Yes. It makes more sense to write:
lock(obj)
{
// Code
}
because this gets expanded into:
Monitor.Enter(obj)
try
{
// code
}
finally()
{
Monitor.Exit(obj)
}
(Forgive typos, I'm just typing it in).
So, lock is exception friendly, whereas just using Monitor Enter/Exit
requires that you
write your own exceptioni handling.
Matt
|