开发者

Calling custom methods on windows service

开发者 https://www.devze.com 2023-01-10 03:02 出处:网络
How can i call custom method on a windows service: public class TestService:ServiceBase { public TestService()

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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消