WebJob大大减慢了我的网站速度

时间:2015-07-13 09:31:04

标签: c# azure azure-web-sites azure-webjobs

我有以下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配置为Singleton。

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

我只是检查并且内存消耗是可以的,但CPU使用率是100%。为什么这样,我该如何解决?

2 个答案:

答案 0 :(得分:5)

尝试:

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做其他事情而不是立即重试。

答案 1 :(得分:1)

您需要在重复呼叫之间休眠。