Powered by Blogger.

Sunday, February 23, 2014

Multithreading tutorial in C#.Net



C#.net supports parallel execution of code through multithreading. A thread is nothing but an execution path to run an application. Multithreading means more than one execution path to run a single application.

Also check out:

Error functions in sql server

Opening one Excel template in Asp.net

Exception Class in C#.Net

C#.Net  program (Console, WPF, or Windows Forms) starts in a single thread created automatically by the CLR and operating system. To convert single threaded application into multithreaded, import System.Threading namespace in your application. Threads are created using the Thread class’s constructor, passing in a ThreadStart delegate which indicates where execution should begin.

using System;
using System.Threading;

class ThreadExample
{
  static void Main()
  {
    Thread t1 = new Thread (new ThreadStart (m1));

    t1.Start();   // Run  method m1() on the new thread.
    m1();        // Simultaneously run  method m1() in the main thread.
  }

  static void m1()
  {
    For(int i=1;i<=100;i++)
    Console.WriteLine ("the value of i is: {0}", i );
  }
}