How to create a Thread in Asp.Net

You can see below how to start a thread when application will start to run, this thread will work even no one browsed the site.

  void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
       Infothread.Start();
    }

Infothread.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Collections;
using System.Net.Mail;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Microsoft.ApplicationBlocks.Data;
using System.Xml.Linq;
using System.Xml;
using System.Configuration;
/// <summary>
/// Summary description for gdthread
/// </summary>
public class  Infothread
{
    private static bool _Cancel = false;
    public static bool Cancel { get { return _Cancel; } set { _Cancel = value; } }
    private static string address = string.Empty;
    private static Thread _mailThread;
    public static Thread mailThread
    {
        get
        {
            if (_mailThread == null || !_mailThread.IsAlive)
                _mailThread = new Thread(InfoData);
           
            return _mailThread;
        }
        set { _mailThread = value; }
    }
    public static void Start()
    {
        _Cancel = false;
        mailThread.Start();
    }
    public static void Abort()
    {
        _Cancel = true;
        mailThread.Abort();
    }
    public static void InfoData()
    {
        while (!_Cancel)
        {
            int min = DateTime.Now.Minute;
            int hour = DateTime.Now.Hour;
            //if (min % 5 == 0 && sec % 20 == 0)
            //{
                try
                {
                    GeofenceAlert();
                    Thread.Sleep(60000);
                   
                }
                catch (Exception ex) {
                  
                }
             
        }
    }
   public static void GeofenceAlert()
    {
        string sqlQuery = "select * from tblcustomers ";
        SqlDataAdapter adp1 = new SqlDataAdapter(sqlQuery, ConfigClass.DbConn);
        DataSet ds = new DataSet();
        adp1.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            for (int LIntCtr = 0; LIntCtr <= ds.Tables[0].Rows.Count - 1; LIntCtr++)
            {
//Add your code here
            }
        }
    }
   
 
    

Related Alrticles

FREE!!! Registration