服务运行时无法更改服务名称

问题描述 投票:1回答:2

我正在尝试启动我的服务,但是我收到以下错误:

服务无法启动。 System.InvalidOperationException:无法在服务运行时更改服务名称。 at System.ServiceProcess.ServiceBase.set_ServiceName(String value)位于\ workgroup.net projects \ Bar \ Bar \ Bar.Designer.vb中的Bar.Bar.InitializeComponent():Bar.Bar.OnStart(String [] args第47行)在\ workgroup.net projects \ Bar \ Bar \ Bar.vb:第22行在System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(对象状态)

我根本不想改变服务名称!什么会导致错误?

Protected Overrides Sub OnStart(ByVal args() As String)
    InitializeComponent()
    writeToLog("in onstart")
    folderToWatch = New FileSystemWatcher
    folderToWatch.Path = sDocDir
    With folderToWatch
        .NotifyFilter = .NotifyFilter Or NotifyFilters.FileName
        .NotifyFilter = .NotifyFilter Or NotifyFilters.Attributes
    End With
    AddHandler folderToWatch.Created, AddressOf ProcessBarCode
    folderToWatch.EnableRaisingEvents = True
End Sub

InitializeComponent功能:

'Required by the Component Designer
Private components As System.ComponentModel.IContainer

' NOTE: The following procedure is required by the Component Designer
' It can be modified using the Component Designer.  
' Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
    'Bar'
    Me.ServiceName = "Bar"

End Sub
.net vb.net
2个回答
2
投票

InitializeComponent()方法调用未正确放置。使用Windows服务项目模板时很难出错,Service1.cs源文件中自动生成的代码如下所示:

    public Service1() {
        InitializeComponent();
    }

换句话说,服务在构造函数运行时获取其名称。哪个很早发生,Program.cs中自动生成的代码如下所示:

    static void Main() {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1()                    // <=== here
        };
        ServiceBase.Run(ServicesToRun);
    }

换句话说,在程序启动之前,在它开始与OS交互并且已经提交到服务名称之前。 OnStart()为时已晚,它是来自操作系统的回调。

因此,请验证构造函数和Main()入口点是否仍然良好。并从OnStart()中删除该调用。


0
投票

我最终在设计师中评论了这一行并解决了这个问题:

<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
    'Me.ServiceName = "Bar"
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.