using System; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using Microsoft.Owin.Hosting; namespace WindowsDataCenter { public partial class DataCenterService: ServiceBase { public DataCenterService() { InitializeComponent(); } private IDisposable _webApp; private bool _stopMainWorkerThread; private Thread _mainWorkerThread; public void Start() { OnStart(new string[] {}); } public void Stop() { OnStop(); } protected override void OnStart(string[] args) { //Initialise the Ninject system. var ninjectInstance = NinjectHelper.GetInstance(); _mainWorkerThread = new Thread(MainWorkerThread) { IsBackground = false, Name = "OWIN SELF HOST MAIN THREAD" }; //TODO: use app.config for endpoint config. try { _webApp = WebApp.Start("http://*:8800"); } catch (Exception ex) { Debug.WriteLine(ex); throw; } } protected override void OnStop() { _webApp.Dispose(); _stopMainWorkerThread = true; if (_mainWorkerThread != null && _mainWorkerThread.IsAlive) { _mainWorkerThread.Join(2000); if (_mainWorkerThread.IsAlive) { _mainWorkerThread.Interrupt(); } } } private void MainWorkerThread() { while (!_stopMainWorkerThread) { Thread.Sleep(2000); } } } }