Threads basics and using ParameterizedThread
implementing multi threading and async process on c#
{
#region Threads
public static void Thredmethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Sub process" + i);
Thread.Sleep(5);
}
}
public static void Mainthread(){
Thread t = new Thread(new ThreadStart(Thredmethod));
t.Start();
for (int i = 0; i < 5; i++)
{
Console.WriteLine("main Thread :"+i);
}
}
#endregion
#region UsingBagroundThread
public static void ThreadMethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Sub process "+i);
Thread.Sleep(1000);
}
}
public static void calingbagroundthread()
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.IsBackground = true;
t.Start();
}
#endregion
#region Parameterizethread
public static void paraThread(Object o)
{
for (int i = 0; i < (int)o; i++)
{
Console.WriteLine("proc method"+i);
}
}
public static void ParameterizesedThreadcaling(){
Thread t = new Thread(new ParameterizedThreadStart(paraThread));
t.Start(5);
t.Join();
}
#endregion
static void Main(string[] args)
{
Mainthread(); // Using threads
//calingbagroundthread();// using baground thread
// ParameterizesedThreadcaling(); // parametirized thread
}
}
Just imagine CPU can process only one process at a time when we are working on Long running operations all other operation should wait until the first process complete,
The remedy for this issue Threading introduced by using threads each thread can complete its own work with out depending or wait for other thread.
certain time period current thread should pause and starts the other thread,
creating a thread with thread class
class Program{
#region Threads
public static void Thredmethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Sub process" + i);
Thread.Sleep(5);
}
}
public static void Mainthread(){
Thread t = new Thread(new ThreadStart(Thredmethod));
t.Start();
for (int i = 0; i < 5; i++)
{
Console.WriteLine("main Thread :"+i);
}
}
#endregion
#region UsingBagroundThread
public static void ThreadMethod()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Sub process "+i);
Thread.Sleep(1000);
}
}
public static void calingbagroundthread()
{
Thread t = new Thread(new ThreadStart(ThreadMethod));
t.IsBackground = true;
t.Start();
}
#endregion
#region Parameterizethread
public static void paraThread(Object o)
{
for (int i = 0; i < (int)o; i++)
{
Console.WriteLine("proc method"+i);
}
}
public static void ParameterizesedThreadcaling(){
Thread t = new Thread(new ParameterizedThreadStart(paraThread));
t.Start(5);
t.Join();
}
#endregion
static void Main(string[] args)
{
Mainthread(); // Using threads
//calingbagroundthread();// using baground thread
// ParameterizesedThreadcaling(); // parametirized thread
}
}
No comments