internal partial class RavenService : ServiceBase
{
 private RavenDbServer server;
 private Task startTask;
 public RavenService()
 {
  InitializeComponent();
 }
 protected override void OnStart(string[] args)
 {
  //单独开启一个线程启动服务
  startTask = Task.Factory.StartNew(() =>
  {
   try
   {
    server = new RavenDbServer(new RavenConfiguration());
   }
   catch (Exception e)
   {
    EventLog.WriteEntry("RavenDB service failed to start because of an error" + Environment.NewLine + e, EventLogEntryType.Error);
    Stop();
   }
  });
  //等待20秒还没有启动则提示
  if(startTask.Wait(TimeSpan.FromSeconds(20)) == false)
  {
   EventLog.WriteEntry(
    "Startup for RavenDB service seems to be taking longer than usual, moving initialization to a background thread",
    EventLogEntryType.Warning);
  }
 }
 protected override void OnStop()
 {
  //异步等待销毁服务
  startTask.ContinueWith(task =>
  {
   if (server != null)
    server.Dispose();
   return task;
  }).Wait();
 }
}