Cannot invoke worker thread in windows service

  • Thread starter Thread starter Vikram
  • Start date Start date
V

Vikram

Thanks Jonathan for the prompt reply.

We have developed a program in C#, originally a windows application, that
was invoking a worker thread. The threading mechanism works fine in this
case. The worker thread gets invoked and an excel file is created.

Currrently, we are trying to convert this program into a windows service. We
have removed any code that writes any kind of output. The service gets
created and we can start it without any error through the component
services. However the worker thread never gets invoked.

We created a totally new solution with a simple windows service project that
just invokes a thread. However, when we ran this service also, the thread
was never invoked. As a simple windows application, it worked.

We even tried using the timer class with the TimerCallback delegate in the
System.Threading namespace.

How can we get threading to work in a windows service?

Many thanks.
Vikram.
 
Vikram said:
How can we get threading to work in a windows service?

Threading works in a Windows Service just as it does anywhere else - for
example the following (which is just the service template with a thread
added) works as expected:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.IO;
using System.Threading;

namespace WindowsService1
{
public class Service1 : System.ServiceProcess.ServiceBase
{

private System.ComponentModel.Container components = null;

public Service1()
{

InitializeComponent();

}


static void Main()
{
System.ServiceProcess.ServiceBase[] ServicesToRun;


ServicesToRun = new System.ServiceProcess.ServiceBase[] { new
Service1() };

System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}


private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}

protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}


protected override void OnStart(string[] args)
{
Thread th = new Thread(new ThreadStart(ThreadThing));
th.Start();
}

private void ThreadThing()
{
StreamWriter sw = new StreamWriter(@"C:\test.out");
sw.WriteLine("That worked!");
sw.Flush();
}


protected override void OnStop()
{

}
}
}

But more complicated examples are fine too, it might be possible that
the thread is running but it is not doing what it is supposed to be due
to permissions or something else. You probably want to add some code in
the thread method that makes some diagnostic output to either a file or
the event log or something.

/J\
 
Back
Top