调试windows服务最简单的方法之一
先看一下这段启动代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
namespace WindowsService1
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
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试试
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!