[英]Pass cmd argument to running process when shutting down windows service
[英]Windows Service Throws Error when Windows is Shutting Down
我有一个使用 .NET 在 C# 中构建的 Windows 服务,每次用户注销、挂起、休眠重置或关机时都会引发错误。 在应用程序事件查看器中,它显示错误如下:-
Application: Service.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ComponentModel.Win32Exception
Exception Info: System.InvalidOperationException
at System.ServiceProcess.ServiceController.GenerateNames()
at System.ServiceProcess.ServiceController.get_ServiceName()
at System.ServiceProcess.ServiceController.Stop()
at WellformationDesktopService.Wellformation+<OnSessionChange>d__3.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.<ThrowAsync>b__6_1(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
似乎失败的操作是使用 System.Net.HTTP.HttpClient 将提交发送到远程 API。 该代码在 Windows 有效关闭用户空间时以外的任何其他时间工作。
我需要做什么才能强制我的服务在无法执行该操作之前触发该操作?
提前致谢。
您可以创建 a.ps(powershell 脚本)来检查要停止的服务,并且脚本会强制运行您的 windows 服务。
以下脚本将解决您的问题。
# start the following Windows services in the specified order:
[Array] $Services = 'Service1','Service2','Service3',...;
# loop through each service, if its running, start it
foreach($ServiceName in $Services)
{
$arrService = Get-Service -Name $ServiceName
write-host $ServiceName
while ($arrService.Status -eq 'Stopped')
{
Start-Service $ServiceName
write-host $arrService.status
write-host 'Service starting'
Start-Sleep -seconds 60
$arrService.Refresh()
if ($arrService.Status -eq 'Running')
{
Write-Host 'Service is now Running'
}
}
}
您可以随时通过Windows Task Scheduler定期运行此脚本。
以及如何自动设置 Windows 服务启动类型。
我们已根据上述@Martheen 的建议纠正了该问题,现在一切正常。 我们忽略 windows 关闭事件,但在启动时查找用户的最后一次注销并将该时间用于结束其 session 并在下次使用机器时提交。
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.