C#开发windows服务如何调试——资料整理

分类: 365bet游戏 时间: 2025-07-02 10:48:40 作者: admin

注意:正常服务的启动时间为30秒左右,当服务启动时间超过30秒会报错!

所以不要在OnStart中做过多的操作,也可以用这种延时的方法启动服务,以防在启动服务时超时。

第二种:

修改源代码(推荐)

找到服务主类中的OnStart方法,由

protected override void OnStart(string[] args)

{

//todo something

}

修改成

public void OnStart()

{

//todo something

}

如下图所示:

注释掉Program.cs文件中的如下代码:

ServiceBase[] ServicesToRun;

ServicesToRun = new ServiceBase[]

{

new Service1()

};

ServiceBase.Run(ServicesToRun);

//修改成

Service1 s1 = new Service1();

s1.OnStart();

//如下图所示:

在OnStart方法中利用F9打断点,然后按下F5就可以进行调试跟踪代码了,如下图所示:

注意:调试时,需要将先前启动的服务首先停止。程序代码编写调试完成后,记得将第1和2步骤的修改还原即可。

--------------------------------------------------

其他参考文章:

文章:Windows服务二:测试新建的服务、调试Windows服务

内容记录日志的地方很有借鉴意义。

文章:https://www.cnblogs.com/dotnet261010/p/6179480.html

文章标题:Windows服务一:新建Windows服务、安装、卸载服务

文章很好的介绍了如何新建和安装服务,当然还有卸载。

安装部分很有借鉴意义,提供了多种方法。

微软资料:https://docs.microsoft.com/zh-cn/dotnet/framework/windows-services/how-to-debug-windows-service-applications

路径:

Docs

.NET

.NET Framework

开发 Windows 服务应用程序

标题:如何:调试 Windows 服务应用程序

文章:C# windows服务的创建与调试

比较全面简洁。

文章:c#写windows服务

示例代码很好,不过具体细节不详细应该都能看懂。

作者的文章有很多赞同。

文章:调试windows服务最简单的方法之一

很好用的方法。

代码示例:

using System;

using System.Collections.Generic;

using System.Linq;

using System.ServiceProcess;

using System.Text;

namespace WindowsService1

{

static class Program

{

///

/// 应用程序的主入口点。

///

static void Main()

{

Service1 s = new Service1();

if (Environment.UserInteractive)

{

s.DebugStart();

Console.ReadKey();

s.DebugStop();

}

else

{

ServiceBase[] ServicesToRun;

ServicesToRun = new ServiceBase[] { s };

ServiceBase.Run(ServicesToRun);

}

}

}

}

关键就在对Environment.UserInteractive的判断上,

请看MSDN上面的解释:

获取一个值,用以指示当前进程是否在用户交互模式中运行。

UserInteractive 属性为运行时无用户界面的 Windows 进程或一个服务(如 IIS)报告 false。 如果此属性为 false,请不要显示模式对话框或消息框,因为没有用来与用户进行交互的图形用户界面。

http://msdn.microsoft.com/zh-cn/library/system.environment.userinteractive(v=VS.100).aspx

然后看一下Service1.cs中的代码:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Diagnostics;

using System.Linq;

using System.ServiceProcess;

using System.Text;

namespace WindowsService1

{

public partial class Service1 : ServiceBase

{

public Service1()

{

InitializeComponent();

}

protected override void OnStart(string[] args)

{

this.ServiceStart();

}

protected override void OnStop()

{

this.ServiceStop();

}

internal void DebugStart()

{

this.ServiceStart();

}

internal void DebugStop()

{

this.ServiceStop();

}

private void ServiceStart()

{

// TODO:

}

private void ServiceStop()

{

// TODO:

}

}

}

最后:更改Project的输出类型

右击该Project,点击Properties,在Application标签中,更改Output Type为Console Application。

OK啦,按F5试试

大佬果然是大佬啊,学习了。