开发者

Windows Service + read from database

I am new To windows service. I need a windows service that reads an entry from a table from database. I have a CONSOLE APP where I add new project WINDOWS SERVICE. I already have a method that access the database, and other methods. I can put a thread on start that reads the database. Wh开发者_Python百科ere do I put the thread? ( how can I do that). Where on WINDOWS SERVICE I add those methods? I have the Windows Service like this:

public Service1()
{
   InitializeComponent();
}

protected override void OnStart(string[] args)
{
   do
   {
      thread.start();
      bool variab = readFromDatabase (Database table);
   }
}

protected override void OnStop()
{
}


I suggest that you create a class in which you do everything you need and create in in the service:

public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        YourClass cl = new YourClass();
        cl.DoWhatYouNeed(...);       
    }

    protected override void OnStop()
    {
    }

This gives you opportunity to run and test your class separate from service, maybe during debug release.


With windows services usually a method is created to execute the main loop of the service, in a separated thread. Otherwise the service could become unresponsive. For example, you can have a method called MainLoop to execute the service logic. Use the OnStart method only to do the initializing tasks, such as read configuration values or start the threads of the service. And use the OnStop to executing cleaning tasks, stopping threads, etc...

Thread _workerThread;
bool _shouldStop;

public Service1()
{
  InitializeComponent();
}    

protected override void OnStart(string[] args)
{
   try{
   _workerThread = new Thread(new ThreadStart(MainLoop));
   _shouldStop = false;
   _workerThread.Start();
   }
   catch{}
}

private void MainLoop()
{
   while (!_shouldStop)
   {
      try{
      //your logic here
      }
      catch{}
   }
}

protected override void OnStop()
{
   _shouldStop = true;
}


You must put your code or class, which contain data access logic in OnStart method

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜