日期:2014-05-20  浏览次数:20724 次

windows服务问题(超高手进)
private bool isrun;

protected override void OnStart(string[] args)
  {

  isrun =true;
  while (isrun)
  {
  try
  {
  StreamWriter sw = File.AppendText(@"d:\myserver.txt");
  sw.WriteLine(string.Format("服务启动,启动时间{0}", DateTime.Now));
  }
  }
  catch (Exception ex)
  {
  WirteWinLog(ex);
  }

  System.Threading.Thread.Sleep(10*1000);
  }

  }

  protected override void OnStop()
  {

  isrun=false;
  StreamWriter sw = File.AppendText(@"d:\myserver.txt");
  sw.WriteLine(string.Format("服务停止,启动时间{0}", DateTime.Now));
  sw.Close();
  }

为什么服务发布后无法停止呢????



------解决方案--------------------
protected override void OnStart(string[] args)
{

System.Timers.Timer aTimer = new System.Timers.Timer();

// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 20000;
aTimer.Enabled = true;

// Keep the timer alive until the end of Main.
GC.KeepAlive(aTimer);
//DataReceive.Listener();

}

protected override void OnStop()
{
timer1.Enabled = false;
}
这样就停了