c# - I need a thread keeping running forever. which method is best? -


i need background long running thread asp.net application. btw,the method fetches external data source period , maybe exception happens, provide ways fullfill task, please advice way best, please advice if there better way.

way1=looping when exception happens.

    static void longrunningmethod()     {                 {             try             {             //fetch external period , maybe exception happens.             thread.sleep(100000);             }             catch(exception ex)             {                 //log exception..             }         } while (true);     }  

way2=running following method period timer, , open new thread when exception happens.

    static void longrunningmethod()     {              try             {             //fetch external period , maybe exception happens.             thread.sleep(100000);             }             catch(exception ex)             {                 //log exception..             thread t2 = new thread(longrunningmethod);             t2.start();             }      }  

way3=call when exception happens.

    static void longrunningmethod()     {              try             {             //fetch external period , maybe exception happens.             thread.sleep(100000);             }             catch(exception ex)             {                 //log exception..                longrunningmethod();             }      }  

i use none of three. in fact, seldom build interval tasks base on asp.net because:

1. start of task out of control

based on asp.net task has started/registered on application_start method, triggered first request, means tasks started when first request comes. theoretically can long time after application deployed.

2. end of task out of control

the web servers (thinking iis) can configured recycle-on-demand (afaik default behavior). is, thread may killed when executing. under circumstances need deal persistence of tasks , states, , add retrying codes , etc... that's nightmare!

for me it's better idea use windows service, or task scheduler function of windows, latter easier because don't need write timer or interval call codes. it's more stable, less code, , friendly logs in event viewer! that's make easier.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -