且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Windows 服务变量生存期

更新时间:2022-06-27 00:19:41

Windows 服务不会比任何其他程序引入更多的生命周期复杂性.唯一的区别是它在后台安静地运行.

A Windows Service doesn't introduce any more lifetime complexities than any other program. The only difference is that it runs quietly in the background.

实现 Windows 服务的 .NET 应用程序继承 ServiceBase 类并覆盖 OnStart 方法.这就是 API 的范围.OnStart 方法负责其他所有事情——如果它只是退出,那么服务也会退出.如果它产生一个新的后台线程或任务来执行它的工作,那么该线程将继续存在.

A .NET application implementing a Windows Service inherits the ServiceBase class and overrides the OnStart method. That's the extent of the API. The OnStart method is in charge of everything else - if it simply exits, then the service exits as well. If it spawns a new background thread or task to perform its work, then that thread will continue to exist.

OnStart 中定义的变量将在该方法退出时超出范围.在类作用域中定义的,或者在从 OnStart 调用的类的作用域中定义的,将与该类实例的生命周期相关联.

A variable defined in OnStart will go out of scope when that method exits. One defined in the class scope, or in the scope of a class that's called from OnStart, will be tied to the lifetime of that class instance.

在不知道您在何处定义变量的情况下,我们无法告诉您它们的生命周期是什么,但作为 Windows 服务运行的可能性不是决定因素.

Without knowing exactly where you're defining your variables, we can't tell you what their lifetime will be, but chances are that running as a Windows Service won't be the deciding factor.