Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to wait for WCF service?

Tags:

c#

.net

wcf

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.

like image 301
bunglestink Avatar asked Jan 12 '11 02:01

bunglestink


2 Answers

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.

like image 150
Reed Copsey Avatar answered Sep 25 '22 13:09

Reed Copsey


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.

like image 24
Josh Avatar answered Sep 21 '22 13:09

Josh