As you might know Thread class has IsAlive property. It is false if the thread method returned or the thread was aborted. So I have an issue with this:
I have a windows service that starts several tasks in different threads. It permanently checks IsAlive property of the threads and if it is false – recreates a task:
foreach (var worker in _workers)
_threads.Add(new Thread(worker.ProtectedRun));
foreach (var thread in _threads)
thread.Start();
while (!EventWaitHandle.WaitOne(0))
{
for (var i = 0; i < _threads.Count; i++)
{
if (!_threads[i].IsAlive)
{
_threads[i] = new Thread(_workers[i].ProtectedRun);
_threads[i].Start();
}
}
EventWaitHandle.WaitOne(1000);
}
But one of the tasks has Timer inside. In ProtectedRun method it starts timer and returns. After method is returned -> Thread’s IsAlive property becomes false -> windows service starts thread again -> infinite loop 🙂
public override void ProtectedRun()
{
_timer = new System.Timers.Timer(24 * 60 * 1000);
_timer.Elapsed += OnTimedEvent;
_timer.Enabled = true;
_timer.Start();
}
Do someone has an idea how to handle this situation? Maybe check thread status instead of IsAlive property?
Well, you ahve a broken design, simply like that.
You run tasks in threads and restart them when they are not alive anymore. GOod.
You have a specific tasks ending immediately but queueing more work on a timer. Good.
Bad news is, though, that the one task and the testing under the first premise are nsimply not compatible.
Choices:
Rework the restart logic or
Keep the thread alive after starting the timer.
Rework it so that there is a specific TASK LEVEL (not thread level) status field to follow.
At the end, your one ProtectedRun method is not following the specifications it should by returning while having active work queued (via the timer).