Question

I have a WCF Service that is hosted by a Console Application. The client connects to the Service through a named pipe. And the Console only gets executed when the client needs it, and the console gets killed after the client is done.

Here is the code that starts and calls the service:

Process hostProcess = Process.Start(info);

//make sure the service is up and running
//todo: find out a better way to check if the service is up and running.
Thread.Sleep(200);

EndpointAddress endpointAddress = new EndpointAddress("net.pipe://localhost/test");
NetNamedPipeBinding binding = new NetNamedPipeBinding();
IHostedService service=hannelFactory<IHostedService>.CreateChannel(binding, endpointAddress);
service.Run();

hostProcess.Kill();

I am using Thread.Sleep to make sure the service is up and running, but that is definitely not the right approach to do so.

So, how can I determine if a WCF service that is hosted in a Console application is up and running?

follow up question, how can i wait for the event to be fired without using Thread.Sleep?

        private static EventWaitHandle GetEventWaitHandle()
    {
        try
        {
            EventWaitHandle eventWaitHandle = EventWaitHandle.OpenExisting(string.Format(serviceStartedEventName, taskIndex));
            return eventWaitHandle;
        }
        catch (Exception)
        {
            //if we do not sleep here, it may cause a stack over flow exceptoin.
            Thread.Sleep(10);
            return GetEventWaitHandle();
        }
    }
Was it helpful?

Solution

You could get the console application to signal an event when its ServiceHost has been opened.


UPDATE

Your starter code should call WaitOne on an instance of your WaitHandle:

EventWaitHandle evtServiceStarted = new EventWaitHandle(...);

Process hostProcess = Process.Start(info); 

//make sure the service is up and running
evtServiceStarted.WaitOne();

// Go ahead and call your service...

Your service host should call Set on a WaitHandle instance pointing to the same named event object:

EventWaitHandle eventWaitHandle = EventWaitHandle.OpenExisting(...);
// Set up the service host and call Open() on it

//... when its all done
eventWaitHandle.Set();

Your service host shouldn't try to open the event more than once - your starter code needs to make sure the event is created (and with the right security permissions) before it kicks off the service application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top