Monitor.Enter/Exit Question

G

Guest

Hi

I've got a CollectData() method which is called by Timer periodically.
CollectData calls Add(input) - the problem is the code after Add(input) in
CollectData() is never executed. It's as if the monitor is never closed.
CollectData() never executes further then Add(input), except I remove the
monitors. It's an Windows CE 5.0 application.

What is my problem? Hope someone can help.

Thanks!

....
protected void CollectData(object oState)
{
Add(input);
.... // code after Add(input)
Do(input); //if some condition met then Do()
...
}

....
public void Add(string input)
{
try
{
Monitor.Enter(strAdded);
this.strAdded += input;
}
catch (Exception oException)
{
throw oException;
}
finally
{
Monitor.Exit(strAdded);
}
}
....
 
M

Markus Stoeger

Rudi said:
Hi

I've got a CollectData() method which is called by Timer periodically.
CollectData calls Add(input) - the problem is the code after Add(input) in
CollectData() is never executed. It's as if the monitor is never closed.
CollectData() never executes further then Add(input), except I remove the
monitors. It's an Windows CE 5.0 application.

What is my problem? Hope someone can help.

What kind of timer are you calling the CollectData method from (there
are three timers in the framework)? Does this timer fire from another
thread?

I think the problem is that the strAdded object gets changed by the +=
operator (as strings can't be modified, += returns a completely new
string / new object instead).

So in effect you are calling Monitor.Enter and Monitor.Exit on two
different objects and the Monitor will never be released on the initial
object.. which can lead to the dead lock you are experiencing.

Try to lock on some object that does not change and see if that helps!

hth,
Max
 
J

Jon Skeet [C# MVP]

Rudi said:
That helped. It was the object I was locking.

Note that if you use lock(...) instead of calling Monitor.Enter/Exit,
the compiler makes sure you lock/unlock the same reference anyway.

In your case, the code would be:

public void Add(string input)
{
lock (strAdded)
{
strAdded += input;
}
}

Locking on that monitor is a bad idea anyway though, precisely because
you're changing the variable value. See
http://www.pobox.com/~skeet/csharp/threads/lockchoice.shtml
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top