调用 Windows 服务上的公共方法
我在 Windows 服务(.NET C#)中有一个计时器。我需要能够从外部程序更改经过的值。如果计时器当前正在运行,我需要能够通过外部程序缩短经过的时间值。我正在考虑在服务中使用一个公共方法来更改计时器经过值并重新启动计时器,但是外部程序可以调用 Windows 服务上的公共方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
简而言之,不可能直接调用另一个进程中的函数。包含您想要访问的函数的进程(在本例中为您的 Windows 服务)需要通过某种 IPC(进程间通信)来公开它。您选择什么类型的 IPC 可能取决于通信需要的复杂程度,以及“客户端”是否是 .NET 应用程序。
如果您的需求很简单(例如,仅设置计时器值),或者如果您的客户端不使用.NET,那么使用命名管道(或 TCP,如果您需要从另一台物理机访问服务)可能是您的最佳选择。命名管道和 TCP 都为您提供了一个 Stream,您可以向其中写入消息并在另一端读取消息。
如果您需要公开许多不同的功能或发送和接收复杂的数据类型,并且如果您在两端都使用 .NET,则 .NET Remoting 或 WCF 可能是最好的。 .NET Remoting 更简单,但有更多限制; WCF 非常灵活,但学习曲线较陡。
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 (e.g. 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.
是的,这是可能的。
您可能需要考虑在服务上创建一个 NetNamedPipe 端点并通过该接口控制服务。
Yes this is possible.
You might want to consider created a NetNamedPipe endpoint on your service and controlling the service through that interface.
例如,您不能直接调用 Windows 服务进程中的方法,但可以让 Windows 服务将此函数公开为 WCF 服务。 Windows 服务也将充当服务主机。这是可能的,而且并不复杂。
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.
较旧的(非 WCF)服务可以使用 .NET Remoting。请查看此处,了解有关如何入门的一些信息。这是 WCF 之前的应用程序之间跨进程边界进行通信的方式。
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.