Alex Rivera | Logout

Deadlock when locking manualResetEvent

Asked 2011-03-16T08:35:53.273
11

I encounter a deadlock caused when locking instance of manualResetEvent. I can't figure out how to solve it. I will appreciate any help.

I have 2 methods in a class performed by different threads:

private ManualResetEvent _event = new ManualResetEvent (true);

private void process(){
  ...
  lock(_event){
    _event.WaitOne();
    ...
  }
}

internal void Stop(){
  _event.Reset();
  lock(_event){
    ...
  }
}

The first thread acuired the lock and is blocked in _event.WaitOne();

The socond thread performed the line _event.Reset(); and is blocked when trying to perform lock(_event).

I thought that when thread 1 is blocked on WaitOne, the lock should be released. I guess I'm wrong. I don't know how can I fix it. b.t.w - I added the lock since the code in the lock block should be synchronized in both threads.

Thanks again and sorry for the long post.

Edit
Report

1 Answer

3

I am guessing you got confused with Monitor.Wait(object) and ManualResetEvent.WaitOne().

Monitor.Wait(object) release the lock and wait until it acquires the lock. ManualResetEvent.WaitOne() blocks the current thread until the event handle gets signaled.

I also recommend not to use ManualResetEvent object as a lock at the same time. Even though the compiler will not generate the error, this is likely going to create confusion as you may have now.

answered 2011-03-16T08:58:56.143

Your Answer