Sign In/My Account | View Cart  

advertisement

AddThis Social Bookmark Button

Article:
  Multithreading with C#
Subject:   Monitor.Enter not working
Date:   2005-08-25 10:34:08
From:   Mambr
Article discusses how one can have more elaborate locking mechanisms in C#, which I have tried before and they seem to fail.


I have a data server, which sends my app some messages and for every message I spawn a thread that tries to access some common code protected by Monitor.Enter(lockObject). This common code sends a reply to a server - server responds and that response releases object lock or calls Monitor.Exit(lockObject). Here is code:


private void sendCallbackMessageToServer(){
Monitor.enter(lockObject);
//do somethign and send message backif conditions are met if not then Monitor.Exit(lockObject)


//do not exit from Monitor here
}


//server sends messages thru this method
private void serverMessageEventHandler(String message){
//yada yada
if(message is the one I am looking for)
//do something and release lock
Monitor.Exit(lockObject);
}


This does not work - it seems to work most of the time, but not always.
I placed increment counter right after Enter and decrement right before exit, which confirmed my suspition - whenever I send duplicate messages the counter is 2 (should be 1 as I start with 0 and write that info to disk before calling Exit).
any help would be greatly appreciated. email is steven_klimov@hotmail.com


Steve



Full Threads Oldest First

Showing messages 1 through 1 of 1.

  • Monitor.Enter not working
    2009-02-08 23:31:55  GhanshyamL [View]

    Steve, check the thread id in which the Monitor.Enter executes. The Monitor.Exit will succeed only if that call happens on the same thread that obtained the lock. This will fail otherwise.

    Maybe Steve will not read this since this seems to be an old post, but this will surely help others, who might read this.

    -Ghanshyam