在Windows服务中创建新的AppDomain实例没有工作

发布于 2025-01-20 09:04:34 字数 996 浏览 6 评论 0原文

我正在尝试使用C#创建Windows服务,该服务在其中催生了多个进程。
并在我的服务的Onstart方法中在启动中创建其中的多个:

    public partial class MyService : ServiceBase
    {
        public ServiceBase()
        {
            InitializeComponents();
        }
    
        protected override void OnStart(string[] args)
        {
            var setup = new AppDomainSetup();
            setup.ApplicationBase = Path.GetDirectoryName(GetMyExePath());
            var ad = AppDomain.CreateDomain("Domain NEW", null, setup);
            var t = new Thread(() => {
                    ad.ExecuteAssembly(GetMyExePath());
                    AppDomain.Unload(ad);
                });
            t.Start();
        }
    }

为此,我正在使用AppDomain功能, 第一个)

当我在控制台应用程序中尝试相同的操作时,它可以正常工作。 但是,当我将其作为Windows服务构建并从Service Manager运行时,它似乎在启动后终止。

打开活动查看器,我看到了有关我的服务的信息:

“无法启动服务。服务的实例已经在运行。”

在没有应用程序域创建代码的情况下运行它可以正常运行。它甚至无法启动一个域,因为它似乎将它们视为试图启动相同的过程,而是在该过程中创建一个新域。

有没有办法让它运行服务,或者仅适用于常规应用程序?

I am trying to create a Windows service with C# which spawns multiple processes inside it.
For this I am using AppDomain functionality and creating multiple of them at startup in the OnStart method of my service:

    public partial class MyService : ServiceBase
    {
        public ServiceBase()
        {
            InitializeComponents();
        }
    
        protected override void OnStart(string[] args)
        {
            var setup = new AppDomainSetup();
            setup.ApplicationBase = Path.GetDirectoryName(GetMyExePath());
            var ad = AppDomain.CreateDomain("Domain NEW", null, setup);
            var t = new Thread(() => {
                    ad.ExecuteAssembly(GetMyExePath());
                    AppDomain.Unload(ad);
                });
            t.Start();
        }
    }

(I know I should put a check to prevent recursively starting new domains from each new one, but for now it doesn't even start the first one)

When I try the same in a Console Application, it works fine.
But when I build it as a Windows Service and run it from the service manager, it seems to terminate after startup.

Opening the Event Viewer, I see this about my service:

"Service can not be started. An instance of the service is already running."

Running it without the app domain creation code works just fine. It fails to start even a single domain as it seems to view them as trying to start the same process twice instead making a new domain within the process.

Is there a way to get this to run on services or does it only work for regular applications?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文