c# - Monitor.Exit() sometimes hangs -


i seem have concurrency problem when using monitor.enter , monitor.exit. code hangs on following monitor.exit statement:

public void endinit() {     monitor.enter(this.lockobj);     this.initcount--;     if (this.initcount == 0) {         this.isinitializing = false;         this.isinitialized = true;         this.oninitialized();     }     // sometimes, exit never return ...     monitor.exit(this.lockobj); } 

there's 1 other place, lockobj used:

public void begininit() {     monitor.enter(this.lockobj);     this.initcount++;     this.isinitializing = true;     this.isinitialized = false;     monitor.exit(this.lockobj); } 

and that's how declare sync object:

private readonly object lockobj = new object(); 

i'm tearing hairs off find out, going on here, no success. i'd expect monitor.enter() block until sync object gets released, why monitor.exit() blocked? can't find explanation behavior in msdn either.

note can't reproduce behavior, occurs rather randomly (well, know "random" not correct wording).

any ideas or helpful hints highly appreciated!

thorsten

i'm making answer previous comment. because should have used try finally construct correctly have monitor.exit being called when exception occurrs in oninitialize().

so code become

public void endinit() {     monitor.enter(this.lockobj);     try     {         this.initcount--;         if (this.initcount == 0) {             this.isinitializing = false;             this.isinitialized = true;             this.oninitialized();         }     }          {         monitor.exit(this.lockobj);         } } 

the same goes second method.

it can written

public void endinit() {     lock(this.lockobj)     {         this.initcount--;         if (this.initcount == 0) {             this.isinitializing = false;             this.isinitialized = true;             this.oninitialized();         }     } } 

edit

a explanation on threading written joe albahari can found here. deserved read.

edit 2 (for completeness)

also stated damien_the_unbeliever, there overload.

this work .net 4 , up. code using monitor become:

public void endinit() {     bool lockacuired = false;     try     {         monitor.enter(this.lockobj, ref lockaquired);         this.initcount--;         if (this.initcount == 0) {             this.isinitializing = false;             this.isinitialized = true;             this.oninitialized();         }     }          {         if(lockaquired)             monitor.exit(this.lockobj);         } } 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -