C# – Windows Listener Service

c++multithreadingtcplistenerwindows-services

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.

Best Solution

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