如何减少Windows服务的高CPU使用率?

时间:2016-11-02 12:51:06

标签: c#

我期待着解决我的Windows服务的特定问题。它使用了大约25%的CPU,我认为,这对于它必须完成的任务而言应该是诚实的。

Windows服务包括3个线程,用作filewatcher。如果创建了特定类型的文本文件,则会根据..

在sql server上启动存储过程

3个filewatchers,因为有3种文件类型,我必须注意。

这是我目前使用的代码:

watcher.cs:

internal class Watcher
    {
        private List<FileSystemWatcher> _fileWatcher;
        private Regex _regex;
        public bool started;

        public Watcher()
        {
            started = false;
            _fileWatcher = new List<FileSystemWatcher>();
            _regex = new Regex(@"(?<=Anz_)(.*)(.txt*@)(.*)");
            initAllWatcher();
        }


        private void initAllWatcher()
        {
            // LBH:
            var watcher = new FileSystemWatcher();
            watcher.Filter = ConfigurationManager.AppSettings["FilterLBH"];
            watcher.Path = ConfigurationManager.AppSettings["FilePath"];
            watcher.Created += onCreated;
            _fileWatcher.Add(watcher);

            // LSC:
            watcher = new FileSystemWatcher();
            watcher.Filter = ConfigurationManager.AppSettings["FilterLSC"];
            watcher.Path = ConfigurationManager.AppSettings["FilePath"];
            watcher.Created += onCreated;
            _fileWatcher.Add(watcher);

            // LEM:
            watcher = new FileSystemWatcher();
            watcher.Filter = ConfigurationManager.AppSettings["FilterLEM"];
            watcher.Path = ConfigurationManager.AppSettings["FilePath"];
            watcher.Created += onCreated;
            _fileWatcher.Add(watcher);
        }

        public void Run()
        {
            foreach (var filewatcher in _fileWatcher)
            {
                filewatcher.EnableRaisingEvents = true;
            }

            started = true;

            Thread.CurrentThread.IsBackground = true;
            Thread.CurrentThread.Priority = ThreadPriority.Lowest;

            while (started)
            {
            }
        }

        private async void onCreated(object Source, FileSystemEventArgs Arg)
        {
            await execute(Arg);
        }

        private async Task execute(FileSystemEventArgs Arg)
        {
            string tablename = _regex.Split(Arg.Name)[1];
            string targetDatabase = _regex.Split(Arg.Name)[3];

            if (tablename.Equals("") == false)
            {
                if (targetDatabase.Equals("") == false)
                {
                    using (var dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString))
                    {
                        var command = new SqlCommand(ConfigurationManager.AppSettings["StoredProcedure"], dbConnection);
                        command.CommandTimeout = dbConnection.ConnectionTimeout;
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.Add("@strParDbTabelle", SqlDbType.VarChar).Value = tablename;
                        command.Parameters.Add("@strParDbSchema", SqlDbType.VarChar).Value = "dbo";
                        command.Parameters.Add("@strParDbName", SqlDbType.VarChar).Value = targetDatabase;

                        try
                        {
                            await command.ExecuteNonQueryAsync();
                        }
                        catch (System.Exception)
                        {
                            throw;
                        }
                    }
                }
            }
        }
    }

的Program.cs:

internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        private static void Main()
        {
            ServiceBase[] ServicesToRun;

            ServicesToRun = new ServiceBase[]
            {
                new BaanJobActiService()
            };

            ServiceBase.Run(ServicesToRun);
        }
    }

因为我将这些行添加到我的代码中:

Thread.CurrentThread.IsBackground = true;
Thread.CurrentThread.Priority = ThreadPriority.Lowest;

如果其他进程需要CPU使用率,CPU使用率会降低到最低限度。这当前有所帮助,但我认为,这不是最终的解决方案。

所以可能你们其中一个人可以教我,我可以改进什么,可能为什么我必须改变它,以获得更好的表现?!

那太棒了!先感谢您。 : - )

PS:我知道我对三位观察者进行初始化的方式并不是最好的方式,但这不应该是我认为的重点......

PPS:我实现了查询异步的执行,因为这是非常长的运行队列,没有这个实现我遇到了超时问题.. ^^

1 个答案:

答案 0 :(得分:0)

Thread.Sleep(10)添加到while循环中为我完成了这项工作。删除循环是不可能的,因为没有它就不能使用filewatcher。

无论如何..这个解决方案将CPU使用率降低到0 - 0.5%,与25-30%相比,这是一个不错的选择!