0

The code runs correctly for a few hour then fail before running again for a few hour...

The project is an web application with WCF service, running on IIS. The BGW is started on Application.Start()

I'm suspecting its because of IIS recycling. Is my approach wrong? how can i make the BGW runs reliably

 public void MyWorks()
        {
            BackgroundWorker worker = new BackgroundWorker();
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler(DoWork);
            worker.RunWorkerAsync();
        }

private static async void DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            int delay = 60;
            while (!worker.CancellationPending)
            {
                await Task.Delay(TimeSpan.FromMinutes(delay));
                //do things here
            }
        }
qkhanhpro
  • 4,371
  • 2
  • 33
  • 45
  • 1
    [How to run background tasks in ASP.Net](http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx) – Damien_The_Unbeliever Dec 12 '16 at 13:42
  • http://stackoverflow.com/questions/536681/can-i-use-threads-to-carry-out-long-running-jobs-on-iis Thanks, after more research from your post, i decided to change the implementation, maybe i'll go with HangFire – qkhanhpro Dec 12 '16 at 13:51
  • Are you disposing the first background worker before running 2nd time? There is some resource the is not being disposed inside the background work. The backgroundworker itself gets disposed when calling the consturctor (new BackgroundWorker) but something inside the worker is not. – jdweng Dec 12 '16 at 13:58
  • @jdweng No, There is only 1 BGW with infinite loop. I dont dispose and construct new BGW – qkhanhpro Dec 12 '16 at 14:02
  • So MyWorks() is only being called once (it creates a new BGW)? Did you verify this? – jdweng Dec 12 '16 at 15:14
  • @jdweng Yes, the original idea was to move a slow processing ranking piece of code to another thread and do it periodically , hence the long await. I'm not sure this is the correct approach but, yes, there is only 1 long living BGW – qkhanhpro Dec 12 '16 at 16:29
  • So did it finish before you attempted to call it a 2nd time? – jdweng Dec 12 '16 at 17:20

1 Answers1

0

I now understand that it is not recommended to run/start BackgroundWorker ( especially with long await/delay ) within the AST.NET web application as it can be (un?)expectedly shutdown

Create an Windows service / Console application / Scheduled tasks where applicable instead

Otherwise, follow this artice

http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx

qkhanhpro
  • 4,371
  • 2
  • 33
  • 45