2

I have created windows service in c# and in that service, I have created 4 threads and running them the background every after 10 sec.

Below is the code:

var ThreadSize = 4;    
for (int i = 0; i < ThreadSize; i++)
{
    Task.Run(async () =>
    {
        while (1 == 1)
        {
            try
            {
                //Logic
                await Task.Delay(10000, cancelSource.Token);
            }
            catch (Exception ex)
            {
                //Log the exception
            }
        }
    });
}

The for loop will be executed only once and will create 4 threads. I am using Task.Delay to wait the thread for 10 sec and then again executing my logic. It will go and execute my logic every 10 sec.

The code is working fine, but after some time, my all threads getting terminated (Not working). I mean, the code in the logic is not working after couples of hours. There is no exception at all. Can any one suggested what went wrong. Thanks you in advance.

Edited Code:

CancellationTokenSource cancelSource;

protected override void OnStart(string[] args)
{
    cancelSource = new CancellationTokenSource();
    Process.StartProcess(cancelSource);
}

protected override void OnStop()
{
    cancelSource.Cancel();
}


public static void StartProcess(CancellationTokenSource cancelSource)
{
    var ThreadSize = 4;
    for (int i = 0; i < ThreadSize; i++)
    {
        Task.Run(async () =>
        {
            while (1 == 1)
            {
                try
                {
                    //Logic
                    await Task.Delay(10000, cancelSource.Token);
                }
                catch (Exception ex)
                {
                    //Log the exception
                }
            }
        });
    }
}
14
  • Show more context, esp. how this connects to the Service.Startup() method.
    – ℍ ℍ
    Apr 17, 2019 at 9:16
  • Posted the code in edited section. Apr 17, 2019 at 9:20
  • I would also check the event logs to see why service stops (if ALL threads are terminated the service would stop) Apr 17, 2019 at 9:21
  • 2
    @peeyushsingh - where do you get that from? The thread that creates the 4 tasks loops and then returns. It shouldn't take even 5 seconds, let alone "run indefinitely" Apr 17, 2019 at 9:25
  • 1
    Logically, the answer is that something is throwing an exception. Which raises the question of why you're not aware of the exceptions. It may be worth adding explicit ContinueWith lambdas configured to run on failure and make sure they're writing the details down somewhere you can find. Apr 17, 2019 at 9:28

2 Answers 2

4

If any exception occurs within the Task.Run, it will be saved and thrown when the task is awaited. You're not awaiting the task, so any exception that has occurred won't be visible.

You should await the Task.Run by either using the await keyword or call .Wait() on it.

As you're spawning multiple tasks, you could add all of them to a list and then call await Task.WhenAny(tasks) which will return when any of the tasks finishes, so you can act accordingly.

Read this article for more information

4
  • Neither is possible/applicable in this (service) scenario.
    – ℍ ℍ
    Apr 17, 2019 at 9:27
  • I don't want to wait for 4 task to complete (Any way this will not completed because of while loop). Lets them run in the background. Apr 17, 2019 at 9:29
  • If you're in a service, you should create a single manager thread and work from there. You can spawn multiple tasks from that thread and wait for any of them to finish (using Task.WhenAny()). They CAN still finish, even if there is an infinite loop in them, because they CAN throw an exception, which will cause the task to stop. Just make sure your manager thread never throws any exception so it can restart the tasks when necessary. Apr 17, 2019 at 9:33
  • Thank you for suggestion but I am confused about it. Any example will be relay appreciated. Apr 17, 2019 at 9:40
1

Your main problem is in

catch (Exception ex)
{
    throw;
}

This effectively means that you don't catch any errors. You might as well remove the try/catch for the same effect, or lack of effect.

The main structure of your Service looks OK, this won't stop by itself. The choice of Task vs Thread is not too important.

Your error happens inside //Logic and is not handled.

You will need some form of logging to find out.

2
  • By bad, Actually I am not through-in any exception. I am login into file. Apr 17, 2019 at 9:31
  • I still not understand what is the exact issue, but I put my logic code in separate private function and then in that private method, I put try and catch block. Then it is working fine. Apr 22, 2019 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.