【问题标题】:How to determine if a WCF service that is hosted in a Console application is up and running?如何确定托管在控制台应用程序中的 WCF 服务是否已启动并正在运行?
【发布时间】:2012-02-11 01:28:24
【问题描述】:

我有一个由控制台应用程序托管的 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();
        }
    }

【问题讨论】:

标签: wcf console named-pipes wcf-hosting


【解决方案1】:

您可以让控制台应用程序在其 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();

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

【讨论】:

  • 谢谢。我刚刚发现 System.Threading.EventWaitHandle 做了同样的事情。
  • BTW EventWaitHandle 相同的东西......也就是说,它是一个围绕 Win32 CreateEvent API 创建的那种名为事件对象的内核的托管包装器。跨度>
  • PS - 这些对象是非托管的内核资源,当你用完它们时需要释放它们。不要忘记在合适的时间对它们调用 Dispose。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-02
  • 2014-05-25
  • 2011-01-26
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多