Thursday, May 26, 2011

.NET and ASP.NET interview Question - Can you explain threading and show its practical implementation?

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:



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.
You will be also interested in watching the below video, which are also asked in most of the interviews and favourable question of interviewers.




Please click here to see more .NET and ASP.NET interview questions

Regards,

Visit Authors blog for more .NET and ASP.Net interview questions

No comments: