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) untilmanualResetEvent.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.