views:

486

answers:

3

How do I write a windows service in c# that listens for tcp connections and processes these connections? The problem is that I want a better method than to "block" in the main thread e.g.

while(true) ;

I can start the listener on another thread but the main thread needs to block to prevent the application from exiting (and the service from stopping). Thanks.

A: 

The best is to probably use a ManualResetEvent which will block until you signal it.

leppie
+1  A: 

Why don't you use a WCF service? - you can host a WCF service in a windows service.... Then you can use NetTcpBinding (in order to communicate through tcp) so our code would look like

namespace WindowsService1
{
    public partial class Service1 : ServiceBase
    {
        internal static ServiceHost myServiceHost = null;

        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            if (myServiceHost != null)
            {
                myServiceHost.Close();
            }
            myServiceHost = new ServiceHost(typeof(WcfServiceLibrary1.Service1));
            myServiceHost.Open();
        }

        protected override void OnStop()
        {
            if (myServiceHost != null)
            {
                myServiceHost.Close();
                myServiceHost = null;
            }
        }
    }
}

Here are some samples: http://www.pluralsight.com/community/blogs/aaron/archive/2008/12/02/screencast-hosting-wcf-services-in-windows-services.aspx http://msdn.microsoft.com/en-us/library/ms733069.aspx

Pavel Nikolov
Agree 100%. It's a job for WCF. I wish I could give you +2. One for suggesting WCF and another for good links.
Vadim
A: 

If you don't use WCF, then TcpListner is the way to go.

As you move forward with this Windows Service you will want some type of "heartbeat" that verifies the service is still running. The simplest way to do this is to have a timer (say, once a minute) update a database. This has the added benefit of keeping the service "alive".

MattH