Jac*_*mit 28 c# service console-application
我想调试一个用C#编写的服务,老式的方式太长了.我必须停止服务,启动我在调试模式下使用服务的应用程序(Visual Studio 2008),启动服务,附加到服务进程,然后在我的Asp.Net应用程序中导航以触发服务.
我基本上让服务在后台运行,等待任务.Web应用程序将触发服务选择的任务.
我想要做的是有一个控制台应用程序来激活服务,以便我调试.有没有人知道的简单演示?
sco*_*ttm 23
您可以在主入口点执行以下操作:
static void Main()
{
#if DEBUG
Service1 s = new Service1();
s.Init(); // Init() is pretty much any code you would have in OnStart().
#else
ServiceBase[] ServicesToRun;
ServicesToRun=new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
#endif
}
Run Code Online (Sandbox Code Playgroud)
并在您的OnStart事件处理程序中:
protected override void OnStart(string[] args)
{
Init();
}
Run Code Online (Sandbox Code Playgroud)
Aar*_*els 16
我总是采用的方法是将所有应用程序的逻辑隔离到类库中.这使得您的服务项目实际上只是一个托管您的类库作为服务的shell.
通过这样做,您可以轻松地对代码进行单元测试和调试,而无需通过附加到进程来处理调试服务的麻烦.我当然建议进行单元测试,但是如果你没有这样做,那么添加一个控制台应用程序,它可以调用与你的服务相同的入口点.
agg*_*ton 13
为了避免使用全局定义,我通常在运行时测试我是通过Environment.UserInteractive属性的服务还是常规应用程序.
[MTAThread()]
private static void Main()
{
if (!Environment.UserInteractive)
{
ServiceBase[] aServicesToRun;
// 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 ServiceMain, New MySecondUserService}
//
aServicesToRun = new ServiceBase[] {new ServiceMain()};
Run(aServicesToRun);
}
else
{
var oService = new ServiceMain();
oService.OnStart(null);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21062 次 |
最近记录: |