Ale*_*psa 32 c# windows-services ipc
我想创建一个Windows服务,验证数据并从另一个Windows应用程序访问它,但我是新的服务,我不知道如何开始.
因此,在服务运行时,Windows应用程序应以某种方式连接到服务,发送一些数据并获得响应,无论是真还是假.
小智 34
我可以成功地处理(几乎)与您执行以下操作相同的问题:
在您的Class:ServiceBase中,代表您的Service类,您可能具有:
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";
}
Run Code Online (Sandbox Code Playgroud)
现在,实施:
protected override void OnStart(string[] args)
{...}
Run Code Online (Sandbox Code Playgroud)
和
protected override void OnStop()
{...}
Run Code Online (Sandbox Code Playgroud)
要处理自定义命令调用:
protected override void OnCustomCommand(int command)
{
switch (command)
{
case 128:
eventLog1.WriteEntry("Command " + command + " successfully called.");
break;
default:
break;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,在您将调用Windows服务的应用程序中使用它:
枚举引用您的方法:(请记住,服务自定义方法总是接收int32(128到255)作为参数并使用Enum使您更容易记住和控制您的方法
private enum YourMethods
{
methodX = 128
};
Run Code Online (Sandbox Code Playgroud)
要调用特定方法:
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);
Run Code Online (Sandbox Code Playgroud)
这样做,您可以控制您的服务.
您可以在此处查看如何创建和安装Windows服务. 有关ExecuteCommand方法的更多信息.
祝好运!
您可以通过使该服务托管 WCF 服务并从您的应用程序连接到它来轻松完成此任务。