0

我使用 vb.net 开发了一个 Windows 服务,它使用OnStart Even 执行以下操作...

  • 从 SQL 表中获取所有条目
  • 从返回的行创建计划

它工作正常,安排他们的时间和东西。

问题:每当我必须向表中添加新行时,我必须重新启动服务,以便它可以抓取新创建的行。这给我带来了问题......可能有一个任务已经在运行并且重新启动服务可能会破坏系统。

那么处理这个问题的最佳方法是什么?可以在不重新启动的情况下将新行加载到服务中吗?

谢谢

4

2 回答 2

1

使用轮询到数据库的概念。使用System.Threading.Timer该类,设置一些间隔,在此之后将调用回调方法并负责轮询数据库以获取新条目。

于 2012-11-29T03:47:09.000 回答
0

OnStart由 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
}

请注意,OnStart可以启动多个线程,也可以根据需要使用启动的第一个线程来启动其他线程。这允许您设置数据库轮询或在消息队列上等待数据的线程。


一个有用的提示:

将 a 添加Main到您的服务允许您在 Visual Studio 中将其作为控制台应用程序运行。这大大简化了调试。

    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);
        }
    }
于 2012-11-29T04:15:40.577 回答