我想创建一个 Windows 服务来验证数据并从另一个 Windows 应用程序访问它,但我是服务的新手,我不确定如何开始。
因此,当服务运行时,Windows 应用程序应该以某种方式连接到该服务,发送一些数据并获得响应,无论是对还是错。
最佳答案
我可以通过以下方式成功处理(几乎)与您相同的问题:
在您的 Class : ServiceBase 中,代表您的服务类,您可能有:
public Class () //constructor, to create your log repository
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("YOURSource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"YOURSource", "YOURLog");
}
eventLog1.Source = "YOURSource";
eventLog1.Log = "YOURLog";
}
现在,实现:
protected override void OnStart(string[] args)
{...}
和
protected override void OnStop()
{...}
处理自定义命令调用:
protected override void OnCustomCommand(int command)
{
switch (command)
{
case 128:
eventLog1.WriteEntry("Command " + command + " successfully called.");
break;
default:
break;
}
}
现在,在调用 Windows 服务的应用程序中使用它:
引用您的方法的枚举:(请记住,服务自定义方法总是接收一个 int32(128 到 255)作为参数,使用枚举可以让您更容易记住和控制您的方法
private enum YourMethods
{
methodX = 128
};
调用特定方法:
ServiceController sc = new ServiceController("YOURServiceName", Environment.MachineName);
ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, Environment.MachineName, "YOURServiceName");//this will grant permission to access the Service
scp.Assert();
sc.Refresh();
sc.ExecuteCommand((int)YourMethods.methodX);
这样做,您可以控制您的服务。
Here您可以查看如何创建和安装 Windows 服务。 More关于 ExecuteCommand 方法。
祝你好运!
关于c# - 如何与Windows服务通信?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4451216/