visual-studio 如何从visual studio运行(F5)windows服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2255335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to run(F5) windows service from visual studio
提问by dotnetcoder
How to run a windows service project from visual studio.
如何从 Visual Studio 运行 Windows 服务项目。
I am building a windows serivce in visual studio 2008, I have to always run the service from control panel and then attach the debugger to running instance of the service. Its kind of annoying since I am cleaning a lot of code and need to restart my service many times during development.
我正在 Visual Studio 2008 中构建 Windows 服务,我必须始终从控制面板运行服务,然后将调试器附加到正在运行的服务实例。这有点烦人,因为我正在清理大量代码并且在开发过程中需要多次重新启动我的服务。
I want to setup my project so as to be able to hit F5 and run the service and directly enter the debug mode. Some tips on how to achieve this would be great.
我想设置我的项目,以便能够按 F5 并运行服务并直接进入调试模式。关于如何实现这一目标的一些提示会很棒。
Thanks in advance!!!
提前致谢!!!
回答by Matt Davis
Copied from here.
从这里复制。
static void Main(string[] args)
{
DemoService service = new DemoService();
if (Environment.UserInteractive)
{
service.OnStart(args);
Console.WriteLine("Press any key to stop program");
Console.Read();
service.OnStop();
}
else
{
ServiceBase.Run(service);
}
}
This should allow you to run from within Visual Studio.
这应该允许您从 Visual Studio 中运行。
Another way would be to embed a programmatic breakpoint in your code by calling System.Diagnostics.Debugger.Break(). When you place this in, say, the OnStart() callback of your service and start your service from the Services console, the programmatic breakpoint will trigger a dialog box that allows you to attach to an existing instance of Visual Studio or to start a new instance. This is actually the mechanism I use to debug my service.
另一种方法是通过调用System.Diagnostics.Debugger.Break(). 当你把它放在你的服务的 OnStart() 回调中并从服务控制台启动你的服务时,编程断点将触发一个对话框,允许你附加到 Visual Studio 的现有实例或启动一个新的实例。这实际上是我用来调试服务的机制。
回答by Samuel Neff
In your Main()routine check for Debugger.IsAttachedand if it's true start your app as if it's a console, if not, call into ServiceBase.Run().
在你的Main()例行检查中Debugger.IsAttached,如果它是真的启动你的应用程序,就好像它是一个控制台,如果不是,调用ServiceBase.Run().
回答by Ryan Kohn
It's possible to set up a companion project to the Windows Service that runs as a console app, but accesses the service methods using Reflection. See here for details and an example: http://ryan.kohn.ca/articles/how-to-debug-a-windows-service-in-csharp-using-reflection/.
可以为作为控制台应用程序运行的 Windows 服务设置一个配套项目,但使用反射访问服务方法。有关详细信息和示例,请参见此处:http: //ryan.kohn.ca/articles/how-to-debug-a-windows-service-in-csharp-using-reflection/。
Here is the relevant code that you'll need in the console application:
以下是您在控制台应用程序中需要的相关代码:
using System;
using System.Reflection;
namespace TestableWindowsService
{
class TestProgram
{
static void Main()
{
Service1 service = new Service1();
Type service1Type = typeof (Service1);
MethodInfo onStart = service1Type.GetMethod("OnStart", BindingFlags.NonPublic | BindingFlags.Instance); //retrieve the OnStart method so it can be called from here
onStart.Invoke(service, new object[] {null}); //call the OnStart method
}
}
}
回答by MannyRamirez
You can also do this: (See comments for explanation)
你也可以这样做:(见注释解释)
public class Program : ServiceBase
{
private ServiceHost _serviceHost = null;
public Program()
{
ServiceName = "";
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if(!DEBUG)
// when deployed(built on release Configuration) to machine as windows service use this
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[] { new Program() };
ServiceBase.Run(ServicesToRun);
#else
// when debugging use this (When debugging after building in Debug Configuration)
//If you want the DEBUG preprocessor constant in Release you will have to check it on in the project configuration
Program progsvc = new Program();
progsvc.OnStart(new string[] { });
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#endif
}
protected override void OnStart(string[] args)
{
// Start Web Service
if (_serviceHost != null)
{
_serviceHost.Close();
}
_serviceHost = new ServiceHost(typeof(Namespace.Service));
_serviceHost.Open();
}
}
回答by Patrick Kafka
Create a seperate project that just references the service project and instantiate and start the service. It just runs like a normal app and you can step into it.
创建一个单独的项目,只引用服务项目并实例化和启动服务。它就像一个普通的应用程序一样运行,你可以进入它。
YourService s = new YourService();
s.Start();
回答by shafyxl
Just call the OnStart() event from the service constructor
只需从服务构造函数调用 OnStart() 事件
I did it in the following way
我是按以下方式做的
public XXX()
{
InitializeComponent();
OnStart(new string[] { "shafi", "moshy" });
}
回答by Pomster
You want to have your windows service as a shell, there should be little code in there so you don't have to test it.
你想让你的 Windows 服务作为一个 shell,那里应该有很少的代码,所以你不必测试它。
You should have every thing you want your service to do in a class.
您应该在课堂上拥有您希望服务完成的所有事情。
You can unit test you class and if it works then reference it to your service.
您可以对您的课程进行单元测试,如果它有效,则将其引用到您的服务中。
This way when you have you class doing every thing you want then when its applied to your service every thing should work. :)
这样,当你让你上课做你想做的每一件事时,当它应用于你的服务时,每件事都应该工作。:)
Will an event log you can see what your service is doing while it is running, also a nice way to test :D try that.
是否会在事件日志中查看您的服务在运行时正在执行的操作,这也是测试的好方法 :D 试试看。
namespace WindowsService
{
public partial class MyService : ServiceBase
{
public MyEmailService()
{
InitializeComponent();
if (!System.Diagnostics.EventLog.SourceExists("MySource")) // Log every event
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog"); // Create event source can view in Server explorer
}
eventLogEmail.Source = "MySource";
eventLogEmail.Log = "MyNewLog";
clsRetriveEmail Emails = new clsRetriveEmail();
eventLogEmail.WriteEntry("Populateing database with mail"); // log event
Emails.EmailGetList(); // Call class
}
protected override void OnStart(string[] args)
{
eventLogEmail.WriteEntry("Started");
}
protected override void OnStop()
{
eventLogEmail.WriteEntry("Stopped");
}
protected override void OnContinue()
{
eventLogEmail.WriteEntry("Continuing");
}
}
}
回答by Pomster
These links can be very helpful when working with services.
这些链接在使用服务时非常有用。
This is a walk though on creating them http://msdn.microsoft.com/en-us/library/zt39148a.aspx
这是创建它们的过程 http://msdn.microsoft.com/en-us/library/zt39148a.aspx
James Michael Hare has on his blog http://geekswithblogs.net/BlackRabbitCoder/written about a really nice template/framework he has made, making it lot easier to develop (and debug) Windows Services: C# Toolbox: A Debuggable, Self-Installing Windows Service Template (1 of 2) http://geekswithblogs.net/BlackRabbitCoder/archive/2010/09/23/c-windows-services-1-of-2-creating-a-debuggable-windows.aspx
James Michael Hare 在他的博客http://geekswithblogs.net/BlackRabbitCoder/ 上写到了他制作的一个非常好的模板/框架,使开发(和调试)Windows 服务变得更加容易:C# 工具箱:一个可调试的、自安装 Windows 服务模板 (1 of 2) http://geekswithblogs.net/BlackRabbitCoder/archive/2010/09/23/c-windows-services-1-of-2-creating-a-debuggable-windows.aspx
It provides you with all the basics you need to quickly get started. And best of all, it give you a really nice way to debug your service as if it was a regular console application. I could also mention that it provides out of the box functionality to install (and uninstall) your service. Part two of the post can be found at this link.
它为您提供了快速入门所需的所有基础知识。最重要的是,它为您提供了一种非常好的方式来调试您的服务,就好像它是一个常规的控制台应用程序一样。我还可以提到它提供了开箱即用的功能来安装(和卸载)您的服务。可以在此链接中找到帖子的第二部分。
I've used this myself a couple of times, and can really recommend it.
我自己用过几次,真的可以推荐它。

