Search This Blog

Friday, March 15, 2013

Basic Threading in C#


Basic Threading in C#:

Threading make your application very smoother. A single thread in a C# application, is an independent execution path that can run simultaneously with the main application thread. C# supports multithreading. And to use the threading namespace, you can directly call it from System.Threading.

Example :

using System;
using System.Threading;

class Program
{
    static void Main()
    {
Thread thread1 = new Thread(new ThreadStart(run));
Thread thread2 = new Thread(new ThreadStart(stop));
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
    }

    static void run()
    {
Thread.Sleep(100);
Console.WriteLine('run');
    }

    static void stop()
    {
Thread.Sleep(1000);
Console.WriteLine('stop');
    }
}

Code Output :
(The threads terminate after 0.1 and 1.0 seconds.)
run
stop

public void SMSThreadFunction()
        {
            try
            {
                if (Convert.ToString(Session["customer_number"]) == string.Empty || Convert.ToString(Session["customer_number"]) == "" || Convert.ToString(Session["customer_number"]) == null)
                {
                    sent_message_ACL(Convert.ToString(Session["MOBILE"]), Convert.ToString(Session["RET_MESSAGE"]));
                    sendsms(Convert.ToString(Session["MOBILE"]), Convert.ToString(Session["RET_MESSAGE"]));
                    LBL_MESS.Text = Convert.ToString(Session["RET_MESSAGE"]);

                }
                else if (Convert.ToString(Session["customer_number"]) != string.Empty || Convert.ToString(Session["customer_number"]) != "")
                {
                    sent_message_ACL(Convert.ToString(Session["MOBILE"]), Convert.ToString(Session["RET_MESSAGE"]));
                    sent_message_ACL(Convert.ToString(Session["customer_number"]), Convert.ToString(Session["Customer_MSG"]));
                    sendsms(Convert.ToString(Session["MOBILE"]), Convert.ToString(Session["RET_MESSAGE"]));
                    sendsms(Convert.ToString(Session["customer_number"]), Convert.ToString(Session["Customer_MSG"]));

                    LBL_MESS.Text = Convert.ToString(Session["RET_MESSAGE"]) + "</br>" + Convert.ToString(Session["Customer_MSG"]);


                }
            }
            catch (Exception ex)
            {
               
            }
        }


Call Function in Threading:

 if (Convert.ToString(Session["UserWeb"]) == "Success")
                {

                    Response.Redirect("../charges.aspx?userid=" + Convert.ToInt32(Session["userid"]));

                }
                else
                {
                    Thread thread = new Thread(new ThreadStart(SMSThreadFunction));
                    thread.Start();
                }

No comments :