2

I need to a background long running thread from the asp.net application. BTW,the method fetches something from external data source period and maybe exception happens, I provide some ways to fullfill this task, please advice which way is best, please advice if there is better way.

Way1=Looping when exception happens.

    static void LongRunningMethod()
    {
        do
        {
            try
            {
            //fetch something from external period and maybe exception happens.
            Thread.sleep(100000);
            }
            catch(Exception ex)
            {
                //log exception..
            }
        } while (true);
    } 

Way2=Running the following method period by something like timer, and open a new thread when exception happens.

    static void LongRunningMethod()
    {

            try
            {
            //fetch something from external period and maybe exception happens.
            Thread.sleep(100000);
            }
            catch(Exception ex)
            {
                //log exception..
            Thread T2 = new Thread(LongRunningMethod);
            T2.Start();
            }

    } 

Way3=Call itself when exception happens.

    static void LongRunningMethod()
    {

            try
            {
            //fetch something from external period and maybe exception happens.
            Thread.sleep(100000);
            }
            catch(Exception ex)
            {
                //log exception..
               LongRunningMethod();
            }

    } 
Jason
  • 1,115
  • 14
  • 25
  • You should use Async-Await or BackGroundWorker or both to accomplish the task. You can google both the terms to know more about it. – Mohit S Aug 29 '16 at 02:07
  • Pay your electric bill and don't unplug the computer. – siride Aug 29 '16 at 02:09
  • Ways 2 & 3 will eventually result in a stack overflow. – SledgeHammer Aug 29 '16 at 02:11
  • @Mohit Shrivastava, what's the benefit compare C# Timer and BackGroundWorker? – Jason Aug 29 '16 at 02:14
  • @SledgeHammer , Yes,stack overflow for way3, why for Way2? – Jason Aug 29 '16 at 02:15
  • @Mohit Shrivastava,BTW, the operation LongRunningMethod() just period, but maybe not time consuming. Maybe the method Name is exactly. – Jason Aug 29 '16 at 02:16
  • @Jason give sometime researching your things. [Timer vs BacgroundWorker](http://stackoverflow.com/questions/19120914/timer-vs-repetitive-background-worker) will compare what I meant to say. – Mohit S Aug 29 '16 at 02:18
  • @Mohit Shrivastava, The LongRunningMethod() just running in the background period(like fetching the data every 3 minutes) to fetch the data from database as there is some updating for the Data in the database , and Save it to the redis, and there is no UI. Based on this information, the Timer is better compare to BackGroundWorker? – Jason Aug 29 '16 at 02:23

2 Answers2

1

I will use none of the three. In fact, I seldom build interval tasks base on ASP.NET because:

1. The start of the task is out of control

Based on ASP.NET the task has to be started/registered on Application_Start method, which is triggered by the first request, that means your tasks is started when the first request comes. Theoretically it can be long time after your application is deployed.

2. The end of the task is out of control

The web servers (thinking IIS) can be configured as recycle-on-demand (AFAIK this is the default behavior). That is, your thread may be killed when executing. Under most circumstances you need to deal with the persistence of your tasks and states, and add retrying codes and etc... That's a nightmare!

For me it's a better idea to use a windows service, or the task scheduler function of windows, the latter is even easier because you don't need to write a timer or interval call codes. It's more stable, less code, and friendly logs in the event viewer! That's really make everything easier.

Cheng Chen
  • 42,509
  • 16
  • 113
  • 174
  • Yes, running it by job, windows service, or the task scheduler function of windows is better, however running it with asp.net is a requirement. the second concern can be fixed by the http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx – Jason Aug 29 '16 at 02:44
  • @Jason - so you've read that blog, and you still want to do this dangerous thing? Why not just run a windows service or scheduled task that calls your asp.net app periodically? – Erik Funkenbusch Aug 29 '16 at 04:32
  • @Erik Funkenbusch , as we don't want to build a separate application for maintenance. – Jason Aug 29 '16 at 06:02
  • @Jason - so you'd rather deal with the fallout and damage of using a tool in a way it's not supposed to be used instead? Regardless, a scheduled task using something like curl to call your web app isn't maintaining an additional application. – Erik Funkenbusch Aug 29 '16 at 14:10
0

I like to use System.ComponentModel.BackgroundWorker:

static BackgroundWorker looper = new BackgroundWorker();
static bool isRunning = true;//you can set this to false when closing
public static void initialize(){
    looper.DoWork+= doLoop;
    looper.RunRunWorkerAsync();
    }
    private static void doLoop(object sender, DoWorkEventArgs e){
        while(isRunning){
           //do looping code
           System.Threading.Thread.Sleep(5000);
               if(!isRunning)
                   break;
        }
    }

PS - sorry for weird spacing - I edited this directly in the code window.

Shannon Holsinger
  • 2,293
  • 1
  • 15
  • 21
  • How about if exception happens when do looping code? Also it seems the BackgroundWorker more suitable for the winform withUI, however I just need to run it as a background thread in the asp.net to fetch the data from database and update it to the cache, there is no UI. – Jason Aug 29 '16 at 02:28
  • BackgroundWorker doesn't require UI. You'd handle exceptions like any other method with try[] catch[]. The benefit to using BW as opposed to a simple loop is that you have built-in status information etc. It's easy to cancel if necessary, check status, and the thread is optimized for background operations. – Shannon Holsinger Aug 29 '16 at 02:39
  • There is always more than one way to skin a cat. I'm offering one of many. Performance isn't an issue here. All methods except @Danny 's deal with loops. Aside from the ones that generate SO, the differences between any will be modest at best. – Shannon Holsinger Aug 29 '16 at 02:45