最近第一次用C#写了一个windows service ,其实实现的内容比较简单。就是启动remoting 连接,但是调试相对初次写windws service 的我来说,比较烦。没有经验,而且没办法像调试其他windows 程序一样设置断点,无法看到运行过程。经过查看一些相关资料后,有了一点点调试的心得。特此留笔,以待今后使用。
相关源码:
static void Main()
{
ServiceBase[] ServicesToRun;
// 同一进程中可以运行多个用户服务。若要将
// 另一个服务添加到此进程中,请更改下行以
// 创建另一个服务对象。例如,
//
// ServicesToRun = new ServiceBase[] {new Service1(), new MySecondUserService()};
//
ServicesToRun = new ServiceBase[] { new TeamWorldService() };
ServiceBase.Run(ServicesToRun);
//TeamWorldService obj = new TeamWorldService();
//obj.OnStart();
}
TeamWorldService :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.IO;
using Tribal.TeamWorld.API;
using Tribal.BaseClasses;
using Tribal.TeamWorld.Remoting;
using Tribal.TeamWorld.Implementation;
namespace Tribal.TeamWorld.Service
{
partial class TeamWorldService : ServiceBase
{
private RemotingInterface _remotingInterface = null;
private MainController _mainController = null;
public TeamWorldService()
{
InitializeComponent();//
}
protected override void OnStart(string[] args)
{
this.AddTextLine("Starting server ( " + DateTime.Now.ToString() + " )");
try
{
this.AddTextLine("Initializing MainController ");
this._mainController = MainController.GetInstance();
}
catch (Exception ex)
{
this.PrintExceptions(ex);
}
if (this._mainController != null)
{
this.AddTextLine("Connecting userinterface to LogController ");
}
try
{
this.AddTextLine("Starting MainController");
this._mainController.Start();
}
catch (Exception exc)
{
this.PrintExceptions(exc);
}
try
{
this.AddTextLine("Starting .NET RemotingInterface");
this._remotingInterface = new RemotingInterface();
this._remotingInterface.StartServing();
}
catch (Exception exc)
{
this.PrintExceptions(exc);
}
}
protected override void OnStop()
{
this._remotingInterface.StopServing();
this._mainController.Stop();
this.AddTextLine("End .NET RemotingInterface");
}
private void PrintExceptions(Exception exc)
{
Exception current = exc;
while (current != null)
{
this.AddTextLine(current.Message);
this.AddTextLine(current.StackTrace);
current = current.InnerException;
}
}
private void AddTextLine(string line)
{
try
{
FileStream fs = new FileStream(@"C:\TeamWorldServiceLog.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine(line+ "\r\n");
m_streamWriter.Flush();
m_streamWriter.Close();
fs.Close();
}
catch (Exception ex)
{
}
}
}
}