views:

30

answers:

3

Hi,

How can i call custom method on a windows service:

public class TestService:ServiceBase
{
   public TestService()
   {
      // constructor
   }

 protected override void OnStart(string[] args)
 {
    // do some work here
 }

 protected override void OnStop()
 {
    // do some work here
 }

 public void TestMethod(int arg)
 {
     // do some work here
 }
}

I know that name of the service is "TestService", so i can do the following:

ServiceController sc = new ServiceController("TestService");

But if I do the following, it doesn't work

sc.TestMethod(5);       // cannot do this

How can i access a method on the service? I am using c#

Thanks.

+1  A: 

You don't typically access methods on a Windows Service. What are you trying to accomplish?

A Windows Service can host a WCF Service which can be accessed from other applications. This may be what you're looking for.

John Saunders
The windows service is processing some requests. Its creating 20 threads. I need to kill one of the threads when a certain condition is met.
S.Baron
Then you should host a little WCF service in the Windows Service. When called, this will set a flag that is visible from the thread you want to have die. When that thread sees the flag set, it will kill itself. In general, it's a bad idea to kill threads.
John Saunders
A: 

You seem to be confused by two different uses of the word "service".

On the one hand there are "service processes", which are long-running background processes that work in the background and are rarely, if ever, visible to the user. That's what you've created above. However, you don't normally call methods directly on such a service--it's a process, not an object.

Then there are "service APIs", which in .NET usually means WCF. A service API is a collection of methods that can be accessed remotely--across processes or even from one computer to another. WCF provides a super-easy way to create and consume such services in .NET.

A "service process" may host a "service API"--in fact, it usually does. But in that case you need to define and invoke your service interface, not just call methods on the ServiceController object.

JSBangs
+1  A: 

You can handle custom commands for Windows Services by implementing ServiceBase.OnCustomCommand, and send them by calling ServiceController.ExecuteCommand.

However, this kind of "command" is just a command identifier between 128 and 256. There are no parameters or return values.

In most cases, this is insufficient, and you have to host a WCF service in your Windows Service, as others have suggested.

Stephen Cleary