I already have some experience in working with threads in Windows but most of that experience comes from using Win32 API functions in C/C++ applications. When it comes to .NET applications however, I am often not sure about how to properly deal with multithreading. There are threads, tasks, the TPL and all sorts of other things I can use for multithreading but I never know when to use which of those options. I am currently working on a C# based Windows service which needs to periodically validate different groups of data from different data sources. Implementing the validation itself is not really an issue for me but I am unsure about how to handle all of the validations running simultaneously. I need a solution for this which allows me to do all of the following things:
- Run the validations at different (predefined) intervals.
- Control all of the different validations from one place so I can pause and/or stop them if necessary, for example when a user stops or restarts the service.
- Use the system ressources as efficiently as possible to avoid performance issues.
So far I've only had one similar project before where I simply used Thread
objects combined with a ManualResetEvent
and a Thread.Join
call with a timeout to notify the threads about when the service is stopped. The logic inside those threads to do something periodically then looked like this:
while (!shutdownEvent.WaitOne(0))
{
if (DateTime.Now > nextExecutionTime)
{
// Do something
nextExecutionTime = nextExecutionTime.AddMinutes(interval);
}
Thread.Sleep(1000);
}
While this did work as expected, I've often heard that using threads directly like this is considered "oldschool" or even a bad practice. I also think that this solution does not use threads very efficiently as they are just sleeping most of the time. How can I achive something like this in a more modern and efficient way? If this question is too vague or opinion-based then please let me know and I will try my best to make it as specific as possible.