是否有比通过Windows服务控制管理器启动服务,然后将调试器附加到线程更简单的方法来逐步遍历代码?这有点麻烦,我想知道是否有更直接的方法。
当前回答
我过去所做的是有一个命令行开关,它可以作为服务或常规应用程序启动程序。然后,在我的IDE中,我将设置开关,以便我可以分步执行我的代码。
对于某些语言,您实际上可以检测它是否运行在IDE中,并自动执行此切换。
你在用什么语言?
其他回答
static class Program
{
static void Main()
{
#if DEBUG
// TODO: Add code to start application here
// //If the mode is in debugging
// //create a new service instance
Service1 myService = new Service1();
// //call the start method - this will start the Timer.
myService.Start();
// //Set the Thread to sleep
Thread.Sleep(300000);
// //Call the Stop method-this will stop the Timer.
myService.Stop();
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}
在开发和调试Windows服务时,我通常通过添加/console启动参数并检查来将其作为控制台应用程序运行。让生活更轻松。
static void Main(string[] args) {
if (Console.In != StreamReader.Null) {
if (args.Length > 0 && args[0] == "/console") {
// Start your service work.
}
}
}
第一行的Debugger.Break()怎么样?
我也认为为正常执行和作为服务提供一个单独的“版本”是可行的,但真的需要为此目的专门提供一个单独的命令行开关吗?
你就不能这样做吗:
public static int Main(string[] args)
{
if (!Environment.UserInteractive)
{
// Startup as service.
}
else
{
// Startup as application
}
}
这将有“好处”,你可以通过双击启动你的应用程序(好吧,如果你真的需要的话),你可以在Visual Studio中点击F5(不需要修改项目设置,包括/控制台选项)。
严格来说,是环境。UserInteractive检查是否为当前窗口站设置了WSF_VISIBLE标志,但是除了作为(非交互式)服务运行之外,还有其他原因它将返回false吗?
这段YouTube视频由Fabio Scopel解释了如何调试一个Windows服务相当好…实际的方法从视频中的4:45开始…
下面是视频中解释的代码…在你的Program.cs文件中,添加Debug部分的东西…
namespace YourNamespace
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
Service1 myService = new Service1();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}
}
在你的Service1.cs文件中,添加OnDebug()方法…
public Service1()
{
InitializeComponent();
}
public void OnDebug()
{
OnStart(null);
}
protected override void OnStart(string[] args)
{
// your code to do something
}
protected override void OnStop()
{
}
它是如何工作的
基本上,你必须创建一个公共void OnDebug(),调用OnStart(string[] args),因为它是受保护的,不能在外部访问。void Main()程序添加了#if预处理器和#DEBUG。
如果项目在DEBUG模式下编译,Visual Studio定义DEBUG。这将允许调试部分(下面)在条件为真时执行
Service1 myService = new Service1();
myService.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
它将像控制台应用程序一样运行,一旦一切顺利,您可以更改模式Release和常规else部分将触发逻辑
推荐文章
- 为什么我不能在c#中有抽象静态方法?
- Nuget连接尝试失败“无法为源加载服务索引”
- net HttpClient。如何POST字符串值?
- 我如何使一个方法的返回类型泛型?
- 何时处理CancellationTokenSource?
- 如何获取正在执行的程序集版本?
- AutoMapper vs valueinjector
- 为什么控制台不。Writeline,控制台。在Visual Studio Express中编写工作?
- 什么是.NET程序集?
- GIT克隆在windows中跨本地文件系统回购
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- 函数应该返回空对象还是空对象?
- 如何转换日期时间?将日期时间
- 如何在c#中连接列表?
- 在c#中引用类型变量的“ref”的用途是什么?