I try to create a Windows Service which listens to UDP port 514, i install it using installutil.exe and i get the following error message:

---------------------------
Services
---------------------------
The SyslogService2005 service on Local Computer started and then stopped. Some services stop automatically if they are not in use by other services or programs.
---------------------------
OK
---------------------------

In practise it starts working till the progressbar in Properties Window ends!

my code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
//using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net.Sockets;
using System.Net;
using MySql.Data;
using MySql.Data.MySqlClient;
using System.Threading;
using System.IO;

namespace SyslogService2005
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
            this.ServiceName = "SyslogServiceUDP514";
            this.CanStop = true;
            this.CanPauseAndContinue = true;
            this.AutoLog = true;
        }

        private const int listenPort = 514;

        class UdpState
        {
            public UdpClient u;
            public IPEndPoint e;
        }


        public static bool messageReceived = false;

        public static bool processWorking = false;

        public static void ReceiveCallback(IAsyncResult ar)
        {
            UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
            IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;


            Byte[] receiveBytes = u.EndReceive(ar, ref e);
            string receiveString = Encoding.ASCII.GetString(receiveBytes);
            LogMessageToFile(receiveString);

            //Console.WriteLine("Received: {0}", receiveString);
            messageReceived = true;


        }



        private static void StartListener()
        {
            // Receive a message and write it to the console.
            //LogMessageToFile("ReceiveMessage");

            IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
            //LogMessageToFile("UdpClient");
            UdpClient u = new UdpClient(e);
            //LogMessageToFile("UdpState");
            UdpState s = new UdpState();
            //LogMessageToFile("s.e = e");
            s.e = e;
           // LogMessageToFile("s.u");
            s.u = u;


            //Console.WriteLine("listening for messages");
            
                //LogMessageToFile("Start Asychronous");
            while (processWorking==true)
            {
                u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

                // Do some work while we wait for a message. For this example,
                // we'll just sleep
                while (!messageReceived)
                {
                    //LogMessageToFile("Sleep 100 ms");
                    Thread.Sleep(100);
                }
            }
            


        }


        static void LogMessageToFile(string msg)
        {
            System.IO.StreamWriter sw = System.IO.File.AppendText("C:\\Services\\LogFile.txt");
            try
            {
                string logLine = System.String.Format("{0:G}: {1}.", System.DateTime.Now, msg);
                sw.WriteLine("+----------------------------------------------------------------+");

                sw.WriteLine(logLine);
            }
            finally
            {
                sw.Close();
            }
        }

        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            //LogMessageToFile("Service Started");

            processWorking = true;

            //StartListener();
            //ThreadStart job = new ThreadStart(StartListener);
            //Thread thread = new Thread(job);
            //thread.Start();
            //LogMessageToFile("StartListener Started");
            StartListener();
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            if ((Thread.CurrentThread != null) && (Thread.CurrentThread.IsAlive))
            {
                processWorking = false;
                Thread.Sleep(5000);
                Thread.CurrentThread.Abort();

                LogMessageToFile("Service Stopped");

            }
        }
    }
}

Dani AI

Generated

Brief diagnosis and quick checklist: since reports the same logic works as a console app but the service "started and then stopped", the usual causes are (1) an unhandled exception during OnStart, (2) OnStart blocking the Service Control Manager (SCM) instead of returning quickly, (3) lack of file or folder permissions for the account the service runs under, or (4) the UDP port already in use. 's note about desktop interaction on Vista is a good reminder: services run in session 0 and must not show UI.

Recommended steps (in order):

  • Inspect Event Viewer (Application and System) right after the service stops for logged exceptions.
  • Confirm the log folder exists and the service account has write permission to it.
  • Check for a port conflict: run netstat to see if UDP 514 is already bound.
  • Make OnStart return quickly by launching a background worker/task; avoid long blocking loops inside OnStart.
  • Wrap listener startup and the receive loop in try/catch and write exceptions to the Event Log so SCM errors become visible.
  • Do not use UI or Thread.Abort in a service.

A robust pattern (use async/task + cancellation, not BeginReceive inside a blocking OnStart):

private CancellationTokenSource _cts;
private Task _listenerTask;
protected override void OnStart(string[] args)
{
    _cts = new CancellationTokenSource();
    _listenerTask = Task.Run(()=> ListenerAsync(_cts.Token));
}
private async Task ListenerAsync(CancellationToken token)
{
    using (var udp = new UdpClient(514))
    {
        while (!token.IsCancellationRequested)
        {
            try
            {
                var res = await udp.ReceiveAsync().ConfigureAwait(false);
                string msg = Encoding.ASCII.GetString(res.Buffer);
                EventLog.WriteEntry("SyslogService", msg, EventLogEntryType.Information);
            }
            catch (ObjectDisposedException) { break; }
            catch (Exception ex) { EventLog.WriteEntry("SyslogService", ex.ToString(), EventLogEntryType.Error); }
        }
    }
}
protected override void OnStop()
{
    _cts?.Cancel();
    _listenerTask?.Wait(TimeSpan.FromSeconds(5));
    _cts?.Dispose();
}

Extra cautions: avoid Thread.Abort, ensure UdpClient is disposed/closed, and use ServiceBase.RequestAdditionalTime only if truly necessary. Running the same worker method from a console Main during debugging makes reproducing the failure much easier.

Recommended Answers

All 7 Replies

If you comment out the logging - does the service still work?

It has the same problem!

Does it work if you tell it it can interact with desktop, or if you run it as you rather than a local service account?

i created a console application with the same functionality and it is working properly!
What the **** with the windows service! The service manager cannot understand that it started ... :(

Depending on which OS and wether you're part of a domain etc, windows 2003 for example is common to have it so you cannot interact with the desktop.. if it thinks for any reaosn you might, the service doesnt work.

What type of interaction? (Development is on Windows Vista)
In most tutorials in OnStart section they create just a event in EventLog or they write service started in a txt file ("Service Started") and they create another event in OnStop section... I just have more functionality in my case...

Inteaction with desktop, eg displaying a form or messagebox, trayicon etc.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.