无法停止 Windows 服务托管网站 API

Unable to Stop Windows Service Hosting Web API

我是 运行 web api 2 作为 windows 服务中的自我托管,在停止期间我打电话 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。

有没有办法优雅地停止服务,知道我不是 运行 停止时的长期任务?

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