简体   繁体   English

调试Windows服务

[英]Debug Windows Service

Scenario 脚本

I've got a windows service written in C#. 我有一个用C#编写的Windows服务。 I've read all the google threads on how to debug it, but I still can't get it to work. 我已经阅读了有关如何调试它的所有谷歌线程,但我仍然无法让它工作。 I've run "PathTo.NetFramework\\InstallUtil.exe C:\\MyService.exe". 我运行了“PathTo.NetFramework \\ InstallUtil.exe C:\\ MyService.exe”。 It said the install was successful, however when I run "Services.msc", The service isn't displayed at all, anywhere. 它表示安装成功,但是当我运行“Services.msc”时,该服务根本不显示在任何地方。 If I go into Task Manager, there is a process called "MyService.vshost.exe". 如果我进入任务管理器,有一个名为“MyService.vshost.exe”的进程。 Pretty sure that's not it, because it's a service, not a process. 很确定不是它,因为它是一种服务,而不是一个过程。

Can Someone Explain To Me? 有人可以向我解释一下吗?

If I am supposed to see the service when I run Services.msc? 如果我在运行Services.msc时应该看到该服务? (Bearing in mind this is all being done on a local machine, with no servers AT ALL. (请记住,这一切都是在本地机器上完成的,没有任何服务器。

Other 其他

I'm running VS2008. 我正在运行VS2008。

EDIT: 编辑:

This is all being done on my local machine, I have no servers or access to any. 这一切都是在我的本地机器上完成的,我没有服务器或访问任何服务器。 Also, I don't even know what the service does, I want to debug it so I can walkthrough the code and see how it all works (the code inside the service, not the service itself - for any of you smarty pants that might suggest I look at a template). 此外,我甚至不知道该服务是做什么的,我想调试它,所以我可以通过代码查看它是如何工作的(服务中的代码,而不是服务本身 - 对于你们任何一个聪明的裤子可能建议我看一个模板)。

EDIT 2: 编辑2:

NONE OF THESE ARE WORKING! 这些都没有工作! Everytime I try something I get some message about having to use NET START or install the service. 每当我尝试一些东西时,我都会得到一些关于必须使用NET START或安装服务的消息。

EDIT 3: 编辑3:

I'm running VS2008. 我正在运行VS2008。

I typed this: C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\InstallUtil.exe C:\\dev\\Restarter\\bin\\Release\\Restarter.exe 我键入:C:\\ WINDOWS \\ Microsoft.NET \\ Framework \\ v2.0.50727 \\ InstallUtil.exe C:\\ dev \\ Restarter \\ bin \\ Release \\ Restarter.exe

I got this: Microsoft (R) .NET Framework Installation utility Version 2.0.50727.3053 Copyright (c) Microsoft Corporation. 我得到了这个:Microsoft(R).NET Framework安装实用程序版本2.0.50727.3053版权所有(c)Microsoft Corporation。 All rights reserved. 版权所有。

Running a transacted installation. 运行事务安装。

Beginning the Install phase of the installation. 开始安装的安装阶段。 See the contents of the log file for the C:\\dev\\Restarter\\bin\\ Release\\Restarter.exe assembly's progress. 请参阅日志文件的内容以获取C:\\ dev \\ Restarter \\ bin \\ Release \\ Restarter.exe程序集的进度。 The file is located at C:\\dev\\Restarter\\bin\\Release\\EDT.Restar ter.InstallLog. 该文件位于C:\\ dev \\ Restarter \\ bin \\ Release \\ EDT.Restar ter.InstallLog。 Installing assembly 'C:\\dev\\Restarter\\bin\\Release\\Restarter.exe'. 安装程序集'C:\\ dev \\ Restarter \\ bin \\ Release \\ Restarter.exe'。 Affected parameters are: logtoconsole = assemblypath = C:\\dev\\Restarter\\bin\\Release\\Restarter.exe logfile = C:\\dev\\Restarter\\bin\\Release\\Restarter.InstallLog 受影响的参数是:logtoconsole = assemblypath = C:\\ dev \\ Restarter \\ bin \\ Release \\ Restarter.exe logfile = C:\\ dev \\ Restarter \\ bin \\ Release \\ Restarter.InstallLog

The Install phase completed successfully, and the Commit phase is beginning. 安装阶段成功完成,提交阶段正在开始。 See the contents of the log file for the C:\\dev\\Restarter\\bin\\ Release\\Restarter.exe assembly's progress. 请参阅日志文件的内容以获取C:\\ dev \\ Restarter \\ bin \\ Release \\ Restarter.exe程序集的进度。 The file is located at C:\\dev\\Restarter\\bin\\Release\\Restar ter.InstallLog. 该文件位于C:\\ dev \\ Restarter \\ bin \\ Release \\ Restar ter.InstallLog。 Committing assembly 'C:\\dev\\Restarter\\bin\\Release\\Restarter.exe'. 提交程序集'C:\\ dev \\ Restarter \\ bin \\ Release \\ Restarter.exe'。 Affected parameters are: logtoconsole = assemblypath = C:\\dev\\Restarter\\bin\\Release\\Restarter.exe logfile = C:\\dev\\Restarter\\bin\\Release\\Restarter.InstallLog 受影响的参数是:logtoconsole = assemblypath = C:\\ dev \\ Restarter \\ bin \\ Release \\ Restarter.exe logfile = C:\\ dev \\ Restarter \\ bin \\ Release \\ Restarter.InstallLog

The Commit phase completed successfully. 提交阶段成功完成。

The transacted install has completed. 事务处理安装已完成。

C:\\Program Files\\Microsoft Visual Studio 9.0\\VC> C:\\ Program Files \\ Microsoft Visual Studio 9.0 \\ VC>

I then went to RUN -> Services.msc I can see nothing in there. 然后我去了RUN - > Services.msc我什么都看不到。

There is a process in Task Manager called "Restarter.vshost.exe". 任务管理器中有一个名为“Restarter.vshost.exe”的进程。

That's it. 而已。

I only wanted to install and debug it. 我只想安装和调试它。 I know it works (as it it runs and doesn't crash). 我知道它有效(因为它运行并且不会崩溃)。 But the code was written by a friend and I want to understand the underlying code by walking through it in debug mode. 但代码是由朋友编写的,我希望通过在调试模式下遍历它来理解底层代码。

I recommend following pattern for debug: 我建议使用以下模式进行调试:

 var ServiceToRun = new SomeService(); 
 if (Environment.UserInteractive)
 {
    // This used to run the service as a console (development phase only)

    ServiceToRun.Start();

    Console.WriteLine("Press Enter to terminate ...");
    Console.ReadLine();

    ServiceToRun.DoStop();
 }
 else
 {
    ServiceBase.Run(ServiceToRun);
 }

Edit: make sure that your target is Console Application, not Windows Application, otherwise it will not work. 编辑:确保您的目标是控制台应用程序,而不是Windows应用程序,否则它将无法正常工作。

you can debug it by attaching the debugger to the process. 您可以通过将调试器附加到进程来调试它。 You can do this by either adding a line to the startup of your program: 您可以通过在程序启动时添加一行来完成此操作:

Debugger.Launch ();

after adding the using statement: 添加using语句后:

using System.Diagnostics; 

you will either need to put that in a conditional block or remove it when you are done debugging 您需要将它放在条件块中,或者在完成调试后将其删除

or by running the service and then attaching to the process manually from the IDE: Debug->Attach to process.. 或者通过运行服务然后从IDE手动附加到流程:Debug-> Attach to process ..

We can make the windows service project debuggable by just adding a parameter and making it behave like a console app. 我们可以通过添加一个参数并使其表现得像一个控制台应用程序来使Windows服务项目可调试。

1) Go to your windows service project properties -> Debug -> Start Options 2) Give an argument -Console 3) Go to Application tab -> output type, change it to Console Application 4) Type the below code in Program.cs 1)转到Windows服务项目属性 - >调试 - >启动选项2)给出参数-Console 3)转到应用程序选项卡 - >输出类型,将其更改为控制台应用程序4)在Program.cs中键入以下代码

static class Program
    {
        private static EventWaitHandle _waitHandle;
        private static Service1 _service;
                static void Main(string[] args)
        {
            bool runConsole = false;**

            foreach (string arg in args)
            {
                if (arg.ToLowerInvariant().Equals("-console"))
                {
                    runConsole = true;
                }
            }   

            _service = new Service1();
            if (runConsole)
            {
                _waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
                Console.WriteLine("Starting Workflow Service in Console Mode");
                Console.WriteLine("Press Ctrl+C to exit Console Mode");
               Console.CancelKeyPress += new ConsoleCancelEventHandler(OnCancelKeyPress);
                _service.InternalStart();
                WaitHandle.WaitAll(new WaitHandle[] { _waitHandle });
            }

            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new Service1() 
            };
            ServiceBase.Run(ServicesToRun);
        }

        static void OnCancelKeyPress(object sender, ConsoleCancelEventArgs e)
        {
            _service.InternalStop();
            _waitHandle.Set();
        }


    }

This has helped me a lot when developing/debugging windows services: 在开发/调试Windows服务时,这对我帮助很大:

http://windowsservicehelper.codeplex.com/ http://windowsservicehelper.codeplex.com/

Just press F5 to debug. 只需按F5即可进行调试。 Very easy. 很容易。

Andrey's approach is also very good. 安德烈的方法也非常好。

In order to be able to debug my service without deploying it, I always write it in the following way: 为了能够在不部署的情况下调试我的服务,我总是以下面的方式编写它:

In your program.cs file: 在program.cs文件中:

#if DEBUG
    MyService myService = new MyService();
    myService.OnDebug();
    System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[]
    {
        new MyService()
    };
    ServiceBase.Run(ServicesToRun);
#endif

and in your MyService.cs file: 并在您的MyService.cs文件中:

    public void OnDebug()
    {
        OnStart(null);
    }

* NOTE * : You must build under 'Release' mode when you are finally done with debugging and you are ready to deploy the service otherwise the service will not be considered as a service. *注意* :当您最终完成调试并准备部署服务时,您必须在“发布”模式下构建,否则该服务将不被视为服务。

Hope this helps. 希望这可以帮助。

Assumptions: 假设:

1) You have the source code available in a Solution in the VS2008 IDE 1)您在VS2008 IDE的解决方案中有源代码

How I Debug C# Services: 我如何调试C#服务:

  1. Install the Service using InstallUtil . 使用InstallUtil安装服务。 (You seem like you've already done that) (你好像已经这样做了)
  2. (If Needed) Change the Service path to the MyService.exe that is produced in your Solution's bin folder (如果需要) 将服务路径更改为在Solution的bin文件夹中生成的MyService.exe
  3. Put something like the following at the beginning of your Service's OnStart() method: 在Service的OnStart()方法的开头添加如下内容:

     while(true) { System.Threading.Thread.Sleep(500); } 
  4. Put a breakpoint on System.Threading.Thread.Sleep(500) System.Threading.Thread.Sleep(500)上设置断点

  5. Build the Solution 构建解决方案

  6. Start your Service using the Windows Service Utility 使用Windows服务实用程序启动服务

  7. While your Service is starting, in VS2008 goto Debug -> Attach To Processes... 在您的服务启动时,在VS2008中转到Debug -> Attach To Processes...

  8. Make sure Show Processes From All Users and Show Processes In All Sessions are checked 确保选中“ Show Processes In All Sessions Show Processes From All Users Show Processes In All Sessions和“ Show Processes In All Sessions中的Show Processes In All Sessions

  9. Find your MyService.exe in the list, and click Attach 在列表中找到您的MyService.exe,然后单击“ Attach

  10. You should now be at the breakpoint you inserted in the infinite loop 您现在应该处于无限循环中插入的断点处

  11. Drag the Control (Yellow Arrow) just outside the infinite loop 拖动控制(黄色箭头) 只是无限循环外

  12. Debug away! 调试一下!

Disclaimer: 免责声明:

Remember to remove the infinite loop when you want to release a build, or when you simply want to run the service normally. 当您想要发布构建时,或者只是想要正常运行服务时,请记住删除无限循环。

It can be that service name is not what you expect and that's why you can't find it. 可能是服务名称不是您所期望的,这就是您无法找到它的原因。 Service name is defined in ServiceInstaller properties in .NET project and does not have to correspond with executable name in any way. 服务名称在.NET项目的ServiceInstaller属性中定义,并且不必以任何方式与可执行文件名对应。 But if you're sure the service is not listed after installation, here is what you can do. 但是,如果您确定安装后未列出该服务,则可以执行以下操作。

First, service installation. 一,服务安装。 There are 2 methods, InstallUtil.exe and SC.exe . 有两种方法, InstallUtil.exeSC.exe First one is tailored specifically for .NET services as it will run all ProjectInstaller and ServiceInstaller code. 第一个是专门为.NET服务定制的,因为它将运行所有ProjectInstallerServiceInstaller代码。 Second one will not do that but it will give you more options and is usually more effective ie likely to succeed where InstallUtil fails. 第二个不会这样做,但它会给你更多的选择,通常更有效,即在InstallUtil失败的情况下可能成功。 This can be when there is an exception in any installer code. 这可能是在任何安装程序代码中出现异常时。

You've already tried installing with InstallUtil so here is SC version: 您已经尝试使用InstallUtil安装,因此这里是SC版本:

sc create MyService binPath= "C:\Service.exe"

Note that MyService is the name you give to the service at this point and it can be anything you like (within reason :-). 请注意, MyService您此时为服务提供的名称,它可以是您喜欢的任何内容(在原因内:-)。 This name will be shown in services console list. 此名称将显示在服务控制台列表中。

Once you have your service installed you would need to debug it right when OnStart is called. 安装服务后,您需要在调用OnStart时进行调试。 This can be achieved by running and attaching to a debugger (Visual Studio) from within the service: 这可以通过从服务中运行并附加到调试器(Visual Studio)来实现:

protected override void OnStart(string[] args)
{
    #if DEBUG
    Debugger.Launch();
    #endif
    ...
}

Do not forget to build and replace service executable after this code change. 在此代码更改后,不要忘记构建和替换服务可执行文件。 Service must be stopped but no need to uninstall and reinstall it. 必须停止服务,但无需卸载并重新安装。

To delete service using SC : 要使用SC删除服务:

sc delete MyService

I recommend to add /test on project properties debug tab as a start option. 我建议在项目属性调试选项卡上添加/test作为启动选项。 Then you can run your service without having to install it. 然后,您可以运行您的服务,而无需安装它。

If your business layer is seperate from the windows service you can test all of your business functions outside of running the windows service. 如果您的业务层与Windows服务分开,则可以在运行Windows服务之外测试所有业务功能。

To test the windows service I like to create a test project that is a console app and I start a new thread that runs my service. 为了测试Windows服务,我想创建一个控制台应用程序的测试项目,然后启动一个运行我的服务的新线程。

System.Threading.Thread sftpThread = new System.Threading.Thread((ThreadStart)service1);
service1.Start();

I recently added this to a project and it works great for me. 我最近将它添加到一个项目中,它对我很有用。 You can debug it just like any other EXE. 你可以像任何其他EXE一样调试它。 After it is added go to your project properties and add a command line parameter (/EXE) in the Debug tab for the Debug build configuration. 添加之后,转到项目属性并在Debug选项卡的Debug选项卡中添加命令行参数(/ EXE)。

<MTAThread()> _
Shared Sub Main()

    '' 
    '' let's add a command line parameter so we can run this as a regular exe or as a service
    ''
    If Command().ToUpper() = "/EXE" Then
        Dim app As MyService = New MyService()

        app.OnStart(Nothing)
        Application.Run()
    Else
        Dim ServicesToRun() As System.ServiceProcess.ServiceBase

        ' More than one NT Service may run within the same process. To add
        ' another service to this process, change the following line to
        ' create a second service object. For example,
        '
        '   ServicesToRun = New System.ServiceProcess.ServiceBase () {New Service1, New MySecondUserService}
        '
        ServicesToRun = New System.ServiceProcess.ServiceBase() {New MyService}

        System.ServiceProcess.ServiceBase.Run(ServicesToRun)
    End If
End Sub

如果使用TopShelf创建服务,则应该能够从Visual Studio轻松调试它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM