22

Windows service running multiple processes using tasks

 3 years ago
source link: https://www.codesd.com/item/windows-service-running-multiple-processes-using-tasks.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Windows service running multiple processes using tasks

advertisements

I have a C# Windows Service that has a Timer that checks every 10 seconds a "flag" in my SQL Table for any Process Pending To Execute.

So right now I have inside my Windows Service:

private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {

    // flag so the process is only executed one at a time.
    if (!_isProcessBusy) {

        RunProcess();

    }
}

private void RunProcessSync() {

    _isProcessBusy = true;

    // ... here all the code for doing the internal process ...

    // when process is Done then change the flag so a new process can be executed
    _isProcessBusy = false;

}

Now I need to let the Windows Service Runs multiple threads of the same process, So if in my SQL Table I have 3 processed to execute then I will let the service run the 3 at the same time.

I was thinking to use System.Threading.Tasks library but don't know if this is the right approach or maybe there is something easier.


There isn't really a question here but:

Yes. You can use Tasks, and async-await, and Parallel. The simplest option here would probably be to use Parallel.Invoke:

Parallel.Invoke(new Action[]
{
    () => RunProcess(1),
    () => RunProcess(2),
    () => RunProcess(3)
});

This will internally use the TaskParallelLibrary, but it's much simpler. more here: Parallel.Invoke() vs. Explicit Task Management


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK