无法停止Windows服务托管Web API

时间:2016-03-25 14:53:24

标签: c# windows-services asp.net-web-api2 self-hosting

我在Windows服务中运行web api 2,在我停止呼叫期间 this.webApp.Dispose();

然而,当我得到以下异常时,这似乎不足以优雅地停止服务:

Failed to stop service. System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.HttpListenerException: Failed to listen on prefix 'http://+:8080/' because it conflicts with an existing registration on the machine.
   at System.Net.HttpListener.AddAllPrefixes()
   at System.Net.HttpListener.Start()
   at Microsoft.Owin.Host.HttpListener.OwinHttpListener.Start(HttpListener listener, Func`2 appFunc, IList`1 addresses, IDictionary`2 capabilities, Func`2 loggerFactory)
   at Microsoft.Owin.Host.HttpListener.OwinServerFactory.Create(Func`2 app, IDictionary`2 properties)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, Cu...

因此,停止服务的唯一方法是获取该服务的PID,然后使用kill-process。

有没有办法优雅地停止服务,知道我没有在停止时执行长任务?

1 个答案:

答案 0 :(得分:0)

发现在stop() Windows服务期间,我实际上正在调用OnStart事件,该事件将启动web api而不是停止它。