WebJob dramatically slows my website down

By : reddy
Source: Stackoverflow.com
Question!

I have the following 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();
        }
    }

The WebJob is configured to be a Singleton.

I use Unity and my LifetimeManager for the DbContext is the PerThreadLifetimeManager. For all other types (which are simple classes not requiring any kind of dispose) a new instance is created every time.

I've just check and the memory consumption is ok but the CPU usage is 100%. Why is that and how can I fix it ?

By : reddy


Answers

You need to sleep your thread between repeating calls.



This video can help you solving your question :)
By: admin