I'm trying to write a multi-threaded app , and I need to use Monitoer.Enter/Exit/Wait/Pulse
I've created a Lock object and used it in its own class like that
public partial class domain
/*I dont sure this is the good practice way to mange DDD Layers (if anybody have a comment about it)*/
{
Public class Peer2PeerCom
{
public static readonly object locker = new object();
//other stuff here
//...
//somwhere here
Monitor.Pulse(locker);
}
}
in the other class I want/need to use the locker like that
public class Control
{
public domain.Peer2PeerCom Dom_P2PCom = new domain.Peer2PeerCom();
internal void connection ( int port , string IpAdress)
{
Monitor.Enter(Dom_P2PCom.locker);
//do stuff here
Monitor.wait(Dom_P2PCom.locker);
//..
Monitor.Exit(Dom_P2PCom.locker);
}
}
But when I try I cannot recognize the locker
, I think it is because it is static
but I dont understand how to correct it without making the entire class static
You're trying to access a static member via a reference. That doesn't work in C#, fortunately - it can lead to very misleading code where it's allowed, e.g. in Java.
Instead, you should use the name of the class to access a static member:
lock (domain.Peer2PeerCom.locker)
{
...
// This should probably be in a while loop...
Monitor.Wait(domain.Peer2PeerCom.locker);
}
(I've used lock
rather than explicitly calling Monitor.Enter
and Monitor.Exit
- it's more idiomatic, and easier to get right - in the code you've given, any exception in the code after entering the monitor would have cause the monitor to be "leaked" - you wouldn't have exited it.)
In general, I'd strongly recommend against using a public static field for a shared lock like this. It makes it much harder to reason about what's using the lock than if it's private within a class. (I'd recommend against public fields in general, along with underscores in class names, classes which are nested for no particular reason, and a class name of domain
, too...)
See more on this question at Stackoverflow