简体   繁体   中英

Calling a public method on windows service

I have a timer in a windows service (.NET C#). I need to be able to change the elapsed value from an external program. If the timer is currently running, I need to be able to shorten the time elapsed value from an external program. I was thinking of having a public method in the service that would change the timer elapsed value and restart the timer, but can an external program call a public method on a windows service?

In short, it's not possible to directly call functions in another process. The process containing the function you want to access (in this case, your Windows service) will need to expose it through some sort of IPC (inter-process communication). What type of IPC you choose will probably depend on how complex the communication needs to be, and whether or not the "client" is a .NET application.

If your needs are simple (eg just setting a timer value), or if your client does not use .NET, using named pipes (or TCP, if you need to access the service from another physical machine) is probably your best bet. Both named pipes and TCP give you a Stream that you can write messages to and read on the other end.

If you need to expose many different functions or send and receive complex data types, and if you are using .NET on both ends, .NET Remoting or WCF is probably best. .NET Remoting is simpler but has more constraints; WCF is very flexible but has a steeper learning curve.

Yes this is possible.

You might want to consider created a NetNamedPipe endpoint on your service and controlling the service through that interface.

NetNamedPipeBinding binding = new NetNamedPipeBinding();
MyService myService = new MyService(binding,
              new EndpointAddress("net.pipe://localhost/MyService"));
myService.ResetTimer(30);

You cannot call a method in a Windows service process directly, but you can have the Windows service expose this function as a WCF service, for instance. The Windows service would be acting as a service host as well. That's possible and not complicated.

Older (non WCF) services can use .NET Remoting. Have a look here for some info on how to get started. This is the pre-WCF way of communicating between applications across process boundaries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM