简体   繁体   English

如何在C#中使while语句中的foreach循环有效

[英]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. 我正在尝试使以下代码更加有效,它可以正常工作,但是占用了12%的处理器资源。 I have a feeling this can be done more nicely. 我觉得这可以做得更好。

this is how my localService looks like: 这是我的localService的样子:

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. 目前,serviceList包含4个localService对象。 I have written this in a console app with the intention to make it a windows service. 我已经在控制台应用程序中编写了此文件,目的是使其成为Windows服务。

If you don't need it to run as fast as possible, you could add a Thread.Sleep(ms); 如果您不需要它尽可能快地运行,则可以添加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. 如果执行时间不长,将导致循环每秒运行约4次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM