Donniewiko
Donniewiko

Reputation: 1683

How to make a foreach loop in a while statement efficient in C#

I am trying to make the following code a bit more efficient, it works as it should but it takes 12% of processor resources. I have a feeling this can be done more nicely.

this is how my localService looks like:

public class localService
{
    public string ID { get; set; }

    public string Name { get; set; }

    public string Server { get; set; }

    public string Status { get; set; }
}

This is the function im trying to improve.

        while (running)
        {
            try
            {
                IEnumerable<localService> serviceList = Startup.ServiceList;
                foreach (var service in serviceList)
                {
                    using (var sc = new ServiceController(service.ID))
                    {
                        if (sc.Status.ToString() != service.Status)
                        {
                            // Do some work here
                        }
                    }
                }
            }

            catch (Exception)
            {
                running = false;
            }
        }

the serviceList contains 4 localService objects at the moment. I have written this in a console app with the intention to make it a windows service.

Upvotes: 0

Views: 125

Answers (1)

TheEvilPenguin
TheEvilPenguin

Reputation: 5672

If you don't need it to run as fast as possible, you could add a Thread.Sleep(ms); in at the end of the loop. It causes your program to do nothing for roughly the number of milliseconds you pass in.

Thread.Sleep(250);

would cause the loop to run about 4 times a second if it doesn't take long to execute.

Upvotes: 1

Related Questions