好的,所以我创建了一个visual studio 2013解决方案,其中包含两个C#项目,一个Win表单应用程序和一个Windows服务。我使用高级安装程序11.6来创建我的安装包,我专门使用内置的服务安装程序功能,这似乎工作正常。
win表单上有一些按钮,当我点击它调用方法的按钮并传递一个数字作为参数(该数字对应于服务的命令)。然后,该方法使用管道将此参数发送到Windows服务。我希望Windows服务始终监听这些命令......当它收到命令代码时,它会启动该操作。
问题是我绝对没有正确的服务结构,我可能错误地使用管道,所以我需要一些建议。我认为我的服务目前只是像脚本一样运行,虽然我不确定。它看起来来自win forms app的命令不仅仅是尝试向服务发送数据,而且似乎正在尝试启动服务的新实例(获取有关无法从服务启动的服务的错误命令行或调试器...但它不应该是*从win表单开始的任何事情。)
无论如何,这里是获胜形式的方法的代码,它将数据发送到服务。
Win Form Method
private void pipe_server(byte _command)
{
//create streams
var sender = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable);
//start client, pass pipe ids as command line parameter
string clientPath = @"C:\\test\\My_Service.exe";
string senderID = sender.GetClientHandleAsString();
var startInfo = new ProcessStartInfo(clientPath, senderID);
startInfo.UseShellExecute = false;
Process clientProcess = Process.Start(startInfo);
//release resources handlet by client
sender.DisposeLocalCopyOfClientHandle();
//write data
sender.WriteByte(_command);
}
这是服务。
public partial class My_Service : ServiceBase
{
public My_Service()
{
InitializeComponent();
}
static void Main(string[] args)
{
System.ServiceProcess.ServiceBase[] ServicesToRun;
//Change the following line to match.
ServicesToRun = new
System.ServiceProcess.ServiceBase[] { My_Service() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
pipe_client(args);
}
//method that listens for commands from the GUI and parses them
static void pipe_client(string[] args)
{
string parentSenderID;
//get pipe handle id
parentSenderID = args[0];
//create streams
var receiver = new AnonymousPipeClientStream(PipeDirection.In, parentSenderID);
//read data
int dataReceive = receiver.ReadByte();
//parse commands
if (dataReceive == 1)
{
do_method_1();
}
else if (dataReceive == 2)
{
do_method_2();
}
else if (dataReceive == 3)
{
do_method_3();
}
}
}
答案 0 :(得分:-1)
此处的示例可帮助您实现您的目标:MSDN
它看起来像你需要做的,设置某种形式的循环来轮询特定命令的流。提供的示例显示了如何设置StreamReader和do循环,该循环检查从StreamReader.ReadLine()命令中提取的字符串,直到识别出某些内容。
//method that listens for commands from the GUI and parses them
static void pipe_client(string[] args)
{
string parentSenderID;
//get pipe handle id
parentSenderID = args[0];
//create streams
var receiver = new AnonymousPipeClientStream(PipeDirection.In, parentSenderID);
using (StreamReader sr = new StreamReader(receiver))
{
// Display the read text to the console
string temp;
// wait for message from server.
do
{
Console.WriteLine("waiting for message...");
temp = sr.ReadLine();
}
while (!<temp in some check variable or array>);
switch(temp)
{
handle everything here.
}
}
}