Unexpected lock/Monitor.Enter() behavior

J

Jeff Gerber

/*

This test program will give a "Value cannot be null" error.

If the lock in this code is removed (or Monitor.Enter()) the program will
run as expected.

I have found no explaination in lock() or Monitor.Enter() documentation as
to why this occurs. I suspect that it is by design of the behind-the-scenes
process that lock uses and is not a bug, however, it would be nice if there
was some documentation to illuminate this process.

If anyone knows otherwise the knowledge is greatly appreciated.

*/

using System;

using System.Threading;

namespace testdelegate

{

delegate void testDelegate();

class Class1

{

private static testDelegate myPrivateDelegate;

public static testDelegate myPublicDelegate

{

set

{

//Monitor.Enter(myPrivateDelegate);

lock(myPrivateDelegate)

{

myPrivateDelegate = value;

}

//Monitor.Exit(myPrivateDelegate);

}

}

[STAThread]

static void Main(string[] args)

{

myPublicDelegate = new testDelegate(DelegateMethod);

lock (myPrivateDelegate)

{

if (myPrivateDelegate != null)

myPrivateDelegate();

}

}

public static void DelegateMethod()

{

Console.WriteLine("executed");

}

}

}
 
J

Jon Skeet

Jeff Gerber said:
This test program will give a "Value cannot be null" error.

Yup - because the first time you try to enter the lock,
myPrivateDelegate is null, and you can't lock on null. Instead, create
another field:

object padlock = new object();

and always lock on that.
 

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