1

i have some quetions regarding Long Running Task that runs when application start. i have created a thread that Runs when asp.net application start in Global.asax(Application_Start) and i abort thread in Global.asax (Application_End)

i want to replace thread with My Task . i have done this way

Thread implementation

t = new Thread(new ThreadStart(() => 
               CheckConnection(emailTo, emailSubject, emailBody)));
t.Start();
_logger.Info("DB Monitor Thread Started ThreadID: " + t.ManagedThreadId);

Task Implementation

Task.Factory.StartNew(
   state =>
       {
           System.Web.HttpContext.Current = (HttpContext)state;
           CheckConnection(emailTo, emailSubject, emailBody);
       },
   System.Web.HttpContext.Current );

Check connection method basically Check that SQl Server is Live and Running or not after set interval and if it fails it send email. my questions are

Check Connection Implementation

while (true)
{
    Thread.Sleep(600000);                

    using (EntityFMContextctx = new EntityFMContext())
    {
        try
        {
            ctx.Connection.Open();                  
        }
        catch (EntityException ex)
        {
            SendEmail(to, subject, body, ex);
        }                   
    }               
}

Questions:

  1. how can i cancel this task like we do Thread.Abort can we cancel this task too?

  2. do we need to Cancel task because when application End or Stop . didnt this Task will be cancelled or aborted automatically. Because application is Ended/Finished.

Can some one guide me how to handle this scenario .any help will be appreciated.

Salman
  • 1,266
  • 5
  • 21
  • 41
  • 1
    Well, it you don't need this thread stopped before process termination and it's abrupt termination will not result in any adverse consequences, (ie important data not flushed or interprocess issues), then sure, just let the OS kill it on process termination. – Martin James Aug 21 '13 at 11:21
  • so u mean to say if i dont do task cancellation then its ok . because when Asp.net application Pool Recycled or Application gets closed . this Task will be killed automatically ? – Salman Aug 21 '13 at 11:23
  • Look up Task Based Asynchronous Pattern (TAP) it will expose CancellationToken. It's also a much nicer pattern for asyncrony and concurrency. – James Jeffery Aug 21 '13 at 19:55

0 Answers0