I am making a basic self hosting WCF service, and I was just wondering what the best way is to have it wait while it accepts requests? All of the basic tutorials I have found simply use Console.ReadLine to wait for the user to hit enter to exit. This does not seem like a very practical for a real application. I tried a while(true); loop, but this consumed all available CPU cycles, so it is not an option. I also tried Thread.Sleep(0), but the service will not accept requests while sleeping, so this also didn't work. I'm sure there is some common way to have your program "stall" to wait for WCF requests; anyone know how?
I am using C#, .NET 3.5 sp1.
If you have this running in a separate thread (since its self hosted), an easy option is to use a ManualResetEvent.
Just call manualResetEvent.WaitOne();
in the WCF thread. This will block (like Console.ReadLine) until manualResetEvent.Set()
gets called from a separate thread.
The nice thing here is that you can have a clean mechanism for shutting down the service, as well.
A real application, if it doesn't have a UI, would probably be better off as a Windows Service. You could set up the WCF service host in the OnStart method of the service and then tear it down in the OnStop.
The reason the examples usually use a console application is because it's easy to demonstrate without confusing the reader with unrelated code to get the service installed and running. But if your server isn't going to have an interactive UI, I would suggest investigating the Windows Service project template.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With