Monitor.Wait outside lock {} - WORKING

120 Views Asked by At

So, i'm developing a project which envolves various clients and servers using TcpChannels

And there is one particular operation that is to freeze a server - making it look slow - it wont respond to any remote call until it is unfreezed. I do this with locks, monitor.wait and monitor.pulse

The problem is that even though i have explicitly defined the channel "timeout" property it wont expire in any case on a freezed server.

so here is a simple example:

the server :

    public class Server
    static void Main(string[] args) {
        HelloService myRem = null;

        TcpChannel channel = new TcpChannel(8086);
        ChannelServices.RegisterChannel(channel, true);

        myRem = new HelloService();
        RemotingServices.Marshal(myRem, "HelloService");

        System.Console.WriteLine("<enter> to exit...");
        System.Console.ReadLine();
    }

    public class HelloServer : MarshalByRef {

        private bool freezed = true;

        public string Hello() {
            while (freezed)
                lock (this)
                    Monitor.Wait(this);

            return "Hello World!";
        }
    }

the client:

public class Client
{
    static void Main()
    {
        IDictionary propBag = new Hashtable();
        propBag["name"] = "tpc";
        propBag["timeout"] = 3000;
        TcpChannel channel = new TcpChannel(propBag, null, null);
        ChannelServices.RegisterChannel(channel, false);
        HelloService obj = (HelloService)Activator.GetObject(typeof(HelloService), "tcp://localhost:8086/HelloService");

        while (true)
        {
            try
            {
                Console.WriteLine(obj.Hello());
            }
            catch (Exception e)
            {
                Console.WriteLine(e.GetType());
                Console.WriteLine("TIMEOUT");
            }
        }
    }
}

On my computer - the call on the client side would never expire

Until I on a desperate tentative removed a lock (this) statement

And the it started to work ! The call receiving the SocketException But now I can understand why since Monitor.wait must always be inside a lock statement

Why is this working on my computer? I've tried in others but i didn't have this problem

EDIT

In fact in other computers i cant get the timeout exception but i do get the Synchronization exception for calling monitor outside lock

0

There are 0 best solutions below