我有一个由控制台应用程序托管的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();
我正在使用Thread.Sleep来确保服务已启动并运行,但这绝对不是正确的方法。
那么,我如何确定控制台应用程序中托管的WCF服务是否已启动并正在运行?
跟进问题,如何在不使用Thread.Sleep的情况下等待事件被触发?
private static EventWaitHandle GetEventWaitHandle()
{
try
{
EventWaitHandle eventWaitHandle = EventWaitHandle.OpenExisting(string.Format(serviceStartedEventName, taskIndex));
return eventWaitHandle;
}
catch (Exception)
{
//if we do not sleep here, it may cause a stack over flow exceptoin.
Thread.Sleep(10);
return GetEventWaitHandle();
}
}
答案 0 :(得分:2)
您可以让控制台应用程序在其ServiceHost打开时发出an event信号。
更新
您的初学者代码应该在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();
您的服务主机不应尝试多次打开事件 - 您的初始代码需要确保在启动服务应用程序之前创建事件(并具有正确的安全权限)。