如何确定托管在控制台应用程序中的WCF服务是否已启动并正在运行?

如何确定托管在控制台应用程序中的WCF服务是否已启动并正在运行?,wcf,console,named-pipes,wcf-hosting,Wcf,Console,Named Pipes,Wcf Hosting,我有一个由控制台应用程序托管的WCF服务。 客户端通过命名管道连接到服务。 控制台只在客户机需要时执行,而控制台在客户机完成后被终止 以下是启动和调用服务的代码: Process hostProcess = Process.Start(info); //make sure the service is up and running //todo: find out a better way to check if the service is up and running. Thread.Sl

我有一个由控制台应用程序托管的WCF服务。 客户端通过命名管道连接到服务。 控制台只在客户机需要时执行,而控制台在客户机完成后被终止

以下是启动和调用服务的代码:

Process hostProcess = Process.Start(info);

//make sure the service is up and running
//todo: find out a better way to check if the service is up and running.
Thread.Sleep(200);

EndpointAddress endpointAddress = new EndpointAddress("net.pipe://localhost/test");
NetNamedPipeBinding binding = new NetNamedPipeBinding();
IHostedService service=hannelFactory<IHostedService>.CreateChannel(binding, endpointAddress);
service.Run();

hostProcess.Kill();

您可以让控制台应用程序在其ServiceHost打开时发出信号


更新

启动程序代码应在WaitHandle的实例上调用WaitOne:

EventWaitHandle evtServiceStarted = new EventWaitHandle(...);

Process hostProcess = Process.Start(info); 

//make sure the service is up and running
evtServiceStarted.WaitOne();

// Go ahead and call your service...
服务主机应在指向同一命名事件对象的WaitHandle实例上调用Set:

EventWaitHandle eventWaitHandle = EventWaitHandle.OpenExisting(...);
// Set up the service host and call Open() on it

//... when its all done
eventWaitHandle.Set();

您的服务主机不应尝试多次打开事件-您的启动程序代码需要确保在启动服务应用程序之前创建了事件(并且具有正确的安全权限)

您能检查承载它的进程是否正在运行吗@kenny进程正在运行并不意味着服务已启动。服务通常需要一段时间才能开始。谢谢。我刚刚发现System.Threading.EventWaitHandle做同样的事情。顺便说一句,EventWaitHandle是同样的事情。。。也就是说,它是围绕Win32 CreateEvent API创建的那种名为event对象的内核的托管包装器。PS-这些对象是非托管内核资源,在使用完它们后需要释放它们。别忘了在适当的时候拜访他们。
EventWaitHandle eventWaitHandle = EventWaitHandle.OpenExisting(...);
// Set up the service host and call Open() on it

//... when its all done
eventWaitHandle.Set();