3 Replies - 7113 Views - Last Post: 13 December 2007 - 03:49 PM Rate Topic: -----

#1 Nayana  Icon User is offline

  • DIC Hawk - 나야나 नयन:
  • member icon

Reputation: 31
  • View blog
  • Posts: 824
  • Joined: 14-November 07

lock(object) {} and return

Posted 12 December 2007 - 01:31 AM

Hello,

I was just wondering if anyone knows offhand whether, for example

lock(anObject) {
  ...
  return false;
  ...
}



Whether the monitor would be released when the return false; command was executed.

???
Is This A Good Question/Topic? 0
  • +

Replies To: lock(object) {} and return

#2 itpro4470  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 156
  • Joined: 17-June 07

Re: lock(object) {} and return

Posted 12 December 2007 - 08:08 PM

not sure off hand if that will work, What I would do is enclose it in an endless loop then break out of the loop when you want to ie...
while(true)
{
	lock(resource)
	{
		.....
		return true;
		break;
		.....
		break;
	}
}


Was This Post Helpful? 0
  • +
  • -

#3 Nayana  Icon User is offline

  • DIC Hawk - 나야나 नयन:
  • member icon

Reputation: 31
  • View blog
  • Posts: 824
  • Joined: 14-November 07

Re: lock(object) {} and return

Posted 12 December 2007 - 09:28 PM

Hmm, if I'm not lazy I'll have a look at what the IL says...

Maybe it would be better just to handle the monitor myself. But that doesn't look as nice :(
Was This Post Helpful? 0
  • +
  • -

#12 skaoth  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 91
  • View blog
  • Posts: 601
  • Joined: 07-November 07

Re: lock(object) {} and return

Posted 13 December 2007 - 03:49 PM

This should exit properly.
I ran code through ildasm that had a lock
statement in it. If you look carefully at the IL code
the lock is transformed into a try/finally block.
So any exiting should trigger the finally block


// Class with lock
	public class Alpha
	{
		public void Beta()
		{
			lock (this)
			{
				while (true)
					Console.WriteLine("Alpha.Beta is runnin in its own thread");
			}
		}
	};



// IL Code
.method public hidebysig instance void  Beta() cil managed
{
  // Code size	   36 (0x24)
  .maxstack  2
  .locals init ([0] class LibTester.learnThreading.Alpha CS$2$0000,
		   [1] bool CS$4$0001)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  dup
  IL_0003:  stloc.0
  IL_0004:  call	   void [mscorlib]System.Threading.Monitor::Enter(object)
  IL_0009:  nop
  .try
  {
	IL_000a:  nop
	IL_000b:  br.s	   IL_0018
	IL_000d:  ldstr	  "Alpha.Beta is runnin in its own thread"
	IL_0012:  call	   void [mscorlib]System.Console::WriteLine(string)
	IL_0017:  nop
	IL_0018:  ldc.i4.1
	IL_0019:  stloc.1
	IL_001a:  br.s	   IL_000d
  }  // end .try
  finally
  {
	IL_001c:  ldloc.0
	IL_001d:  call	   void [mscorlib]System.Threading.Monitor::Exit(object)
	IL_0022:  nop
	IL_0023:  endfinally
  }  // end handler
} // end of method Alpha::Beta



Was This Post Helpful? 1

Page 1 of 1