Logic for Windows Services & Getting Updates

主宰稳场 提交于 2019-12-13 07:34:10

问题


I developed a Windows service using vb.net which does the following using OnStart Even...

  • Grabs all Entries from a SQL Table
  • Creates Schedules from returned rows

it works fine, schedules fire on their time and stuff.

Problem: Whenever I have to ADD a new row to my Table, I have to restart the Service, So it can Grab the Newly created rows. This is causing problems for me...there could be a task which is running already and restarting service might break the system.

So what is the best way to handle this? Can the new rows be loaded into Service without a restart?

Thanks


回答1:


This OnStart was provided here by Marc Gravell:

public void OnStart(string[] args) // should this be override?
{
    var worker = new Thread(DoWork);
    worker.Name = "MyWorker";
    worker.IsBackground = false;
    worker.Start();
}
void DoWork()
{
    // do long-running stuff
}

Note that OnStart can launch multiple threads or the first thread started may be used to start additional threads as needed. This allows you to set up either database polling or a thread that waits on a message queue for data.


A useful tip:

Adding a Main to your service allows you to run it as a console application in Visual Studio. This greatly simplifies debugging.

    static void Main(string[] args)
    {
        ServiceTemplate service = new ServiceTemplate();
        if (Environment.UserInteractive)
        {
            // The application is running from a console window, perhaps creating by Visual Studio.
            try
            {
                if (Console.WindowHeight < 10)
                    Console.WindowHeight = 10;
                if (Console.WindowWidth < 240) // Maximum supported width.
                    Console.WindowWidth = 240;
            }
            catch (Exception)
            {
                // We couldn't resize the console window.  So it goes.
            }

            service.OnStart(args);
            Console.Write("Press any key to stop program: ");
            Console.ReadKey();
            Console.Write("\r\nInvoking OnStop() ...");
            service.OnStop();

            Console.Write("Press any key to exit: ");
            Console.ReadKey();
        }
        else
        {
            // The application is running as a service.
            // Misnomer.  The following registers the services with the Service Control Manager (SCM).  It doesn't run anything.
            ServiceBase.Run(service);
        }
    }



回答2:


Use the concept of Polling into the Database. Use the System.Threading.Timer class, set some interval after which a callback method will be invoked and that will be responsible to Poll the Database for new entries.



来源:https://stackoverflow.com/questions/13618277/logic-for-windows-services-getting-updates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!