.NET and ASP.NET interview Question - What is Threading and how to implement it?

 Posted by ArticlesMaint on 5/23/2011 | Category: C# Interview questions | Views: 12479


Threading is a parallel processing unit and helps you to access multiple tasks at a one moment of time. When we want to access parallel processing in our application we use Threading.


In order to use threading we first have to import System.Threading namespace in our application like below code.
using System.Threading;


Below is the simple class in which I have defined two functions as Fun1 and Fun2.i have also created a DoTest function with an instance of thread as t1 and t2.finally I have invoked DoTest function in Main Method.

class Program   

{
 public void Fun1()      
{
  for (int i = 0; i < 10; i++)         
{              
Console.WriteLine("i"+"="+i.ToString());              
Thread.Sleep(500);         
}       
}
 public void Fun2()       
{
  for (int j = 0; j < 10; j++)           
{               
Console.WriteLine("j" + "=" +j.ToString());             
Thread.Sleep(500);      
}        
}
  static void Main(string[]args)       
{
   Program p = new Program();        
   p.DoTest();
   Console.ReadLine();       
}
  public void DoTest()       
{
  Thread t1 = new Thread(new ThreadStart(Fun1));     
  Thread t2 = new Thread(new
  ThreadStart(Fun2));
  t1.Start();
  t2.Start();       
}
}

Once you have completed the above steps just run your application and you will see the output like below diagram.
Output:


aa.png


You can see that in the above diagram both the function Fun1 and Fun2 run at single moment of  time with one after another and display their respective outputs. 


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response