why use Monitor.Enter...Monitor.Exit insted of lock(object9

  • Thread starter Thread starter Tony Johansson
  • Start date Start date
T

Tony Johansson

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 ?

//Tony
 
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
 
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 ?

Using the two Monitor methods gives you more
control than the lock { }.

In most cases lock { } is fine, but in some cases
you may want more control - like doing Monitor.Exit
different places depending on some variables.

Arne
 
Back
Top