WebJob 大大降低了我的网站速度

WebJob dramatically slows my website down

我有以下 WebJob:

    static void Main(string[] args)
    {

        Bootstrap(); //IoC container config

        System.Diagnostics.Trace.TraceInformation("Entering the main loop");
        while (true)
        {
            OrdersFetcher.DoWork();
        }
    }

    public static class OrdersFetcher
    {
        const int MINIMUM_NUMBER_OF_SECONDS_BETWEEN_FETCHES = 10;
        static DateTime _lastFetchDate = DateTime.UtcNow.AddSeconds(int.MinValue);
        static bool _currentlyRunning = false;

        public static void DoWork()
        {
            if (DateTime.UtcNow - _lastFetchDate < TimeSpan.FromSeconds(MINIMUM_NUMBER_OF_SECONDS_BETWEEN_FETCHES))
                return;

            if (_currentlyRunning)
                return;

            _currentlyRunning = true;
            _lastFetchDate = DateTime.UtcNow;
            Task.Factory.StartNew(() => { FetchOrders(); }).ContinueWith((task) =>
            {
                _currentlyRunning = false; Console.WriteLine("**** Orders Fetching Ended ****");
            });

        }

        private static FetchOrders()
        {
            var db = Program.container.Resolve<MyDbContext>();
            //Fetch from third party and add changes to DbContext
            db.SaveChanges();
            db.Dispose();
        }
    }

WebJob 配置为单例。

我使用 Unity,我的 DbContext LifetimeManager 是 PerThreadLifetimeManager。对于所有其他类型(简单 类 不需要任何类型的处置)每次都会创建一个新实例。

我刚刚检查过,内存消耗正常,但 CPU 使用率为 100%。为什么会这样,我该如何解决?

尝试:

if (DateTime.UtcNow - _lastFetchDate < TimeSpan.FromSeconds(MINIMUM_NUMBER_OF_SECONDS_BETWEEN_FETCHES))
                Thread.Sleep((long)DateTime.UtcNow.Substract(_lastFetchDate). TotalMilliseconds);

而不是:

if (DateTime.UtcNow - _lastFetchDate < TimeSpan.FromSeconds(MINIMUM_NUMBER_OF_SECONDS_BETWEEN_FETCHES))
                return;

这样您的线程将离开 CPU 做其他事情而不是立即重试。

您需要在重复调用之间休眠您的线程。