简体   繁体   中英

Best way to implement windows service as “worker”

I have an ASP .NET page which allows users to start programs. These programs and the parameter are stored in a database and a windows service then executes these programs. The programs are dlls which implements my IPlugin interface, so I can add them at runtime (the dlls are loaded at runtime so I can add them at runtime without compiling or restarting the service).

I created the ASP .NET page, more than 10 programs (plugins) and the windows service. Everything is running fine, but I think the implementation of the windows service is bad.

The windows service periodically queries the database and executes the needed program if it gets a new entry. The service can run multiple programs in parallel (at the moment 3 programs).

Currently my service method looks like this:

 while (Alive)
        {
                // gets all running processes from the database
                Processes = Proc.GetRunningProcs();

                // if there are less than 3 processes running and
                // a process is in queue
                if (ReadyToRun())
                {
                    // get next program from queue, sets the status to 
                    // runnig and update the entry in the database
                    Proc.ProcData proc = GetNextProc();
                    proc.Status = Proc.ProcStatus.Running;
                    Proc.Update(proc);

                    // create a new thread and execute the program
                    Thread t = new Thread(new ParameterizedThreadStart(ExecuteProc));
                    t.IsBackground = true;
                    t.Start(proc);
                }

            Thread.Sleep(1000);
        }

I have a method that queries the database for entries with status 'Canceling' (if a user cancels a program, the status will be set to 'Canceling') and does a Thread.Abort().

Is there a better practice? Like using tasks with the cancel mechanism or is the whole concept (storing the processes in database (program name, parameter, status,... and querying this information periodically) wrong?

As an alternative you can use some existing libraries for your purposes like Quartz.NET http://www.quartz-scheduler.net/ . It takes care about job persistence, job scheduling and many other things. All you must do to create an adapter and put it into Windows Service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM