Hi

I Create service using C#.I use the coding part of test to create servicee.Once I start the service it gave me message saying

"Myservice on local computer started and then stoped.Some services
stop automaticaly if they have no work to do,for example ,the performance logs and alerts service"

below I mention the coding part

protected override void OnStart(string[] args)
        {



            eventLog1.WriteEntry("Test", EventLogEntryType.Information);
            FileStream fs = new FileStream(@"c:\temp\mcWindowsService.txt", FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter m_streamWriter = new StreamWriter(fs);
            m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
            m_streamWriter.WriteLine(" mcWindowsService: Service Started \n");
            m_streamWriter.Flush();
            m_streamWriter.Close();
        }

I write the coding for Stop function.Please help me to slove this problem.

Dani AI

Generated

Short answer: the service is stopping because either OnStart threw an unhandled exception, or OnStart returned without launching any ongoing work. As pointed out, Windows expects OnStart to return quickly and for the service to perform ongoing work on another thread/timer. The message you saw (“some services stop automatically…”) is Windows telling you the service finished its startup routine without anything left to do.

Do these checks first:

  • Look in Event Viewer (Application and System logs) for errors from your service — an exception in OnStart will be recorded there.
  • Make sure the folder you write to exists and the service account has write rights (services often run under LocalSystem or NetworkService).
  • Wrap OnStart in try/catch and log any exception to a file or the EventLog so you can see failures during startup.

A safe pattern is to start a background worker (Task or Timer) in OnStart and stop it in OnStop. Example pattern (very small, complete idea):

// fields
CancellationTokenSource _cts;

// OnStart
_cts = new CancellationTokenSource();
Task.Run(() => Worker(_cts.Token));

// OnStop
_cts.Cancel();

// worker loop
void Worker(CancellationToken token) {
  while (!token.IsCancellationRequested) {
    // do periodic work, then wait
    Thread.Sleep(1000);
  }
}

Notes and tips:

  • Using System.Timers.Timer is an alternative to a worker loop and is simpler for periodic tasks.
  • If you need the interactive user's account name (as asked), remember a service runs in its own session; calls that read environment/user for the current process will return the service account, not the logged-on interactive user. Detecting interactive users requires session APIs or a helper process running in the user session.
  • As suggested, follow a tried tutorial while you test. Add logging and run the service as a console app during debug to simplify troubleshooting.

Recommended Answers

All 6 Replies

I think you need to launch a thread in the OnStart() to keep the service alive. When a Service calls the OnStart() it does not report the service as "running" until the main thread finishes -- and it probably has to have another thread to keep it alive.

Unlike form applications that block the main thread until the application exits, windows will hold on to the main service thread.

Hi

I am not good at thread.is there another way to do this.

Tank50

You can drop a timer in your service and have the timer fire off on an interval

I hope this and this will help you.

Hi,

I would like to ask if i intend to copy or capture the windows login name, how am i to go about doing it?

I tried

string Name = Environment.GetEnvironmentVariable("USERNAME");
string FirstPresentTime = DateTime.Now.ToString();

then write it to txt file but the name is blank but the Date&time appeared and if i change it to

string Name = ("USER");

the USER and Date&time will both appear.

Thanks,
keat

I think you should start new thread for such question. but before this search in this forum regarding your problem.

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.