Asynchronous Threading






1.16/5 (23 votes)
Apr 20, 2004

65563

1198
Asynchronous Threading Using C#
Introduction
This code demonstrate how easily one can create a asynchronouse processes using .net threading.
Why Use Asynchronouse Threading:
Let' say you have a budle of requests to save data then you need to use threading
other wise system will wait for first request to be completed and then awoke function for sencond request.
By using threading always a new instance of of your function will be created and many instances will be running togeather, and data will be saved parrally from application end.
What you have to do:
Create a function that will be called rapidly.
Suppose
void
SaveUser(int id,string name){...}
Now create a function that will create thread and add this function to it...
void dosave(id,name){
t=new Thread (new
ThreadStart(SaveUser(id,name)));
}
On each request of save data call above function...
dosave(1,"jhon smith");
What you have to include to use threading
You have to include threading name space in order to use the threading class.
using
System.Threading;
Form1.cs
private void Form1_Load(object sender, System.EventArgs e)
{
//to track maximum request count
count=0;
//set text for button 1
button5.Text ="Start Thread 1 ";
}
private void button5_Click(object sender, System.EventArgs e)
{
//incremnet in count and maximun count can be 4
if ((count+1)<=4){
count++;
//create a new theread that will start function "StartThread"
t=new Thread (new ThreadStart(StartThread));
//add thread to a hash table so that you can handle each instance of the thread.
threadHolder.Add(threadCount++,t);
//Give some name to thread
t.Name = "Thread ID: "+threadCount;
t.IsBackground = true;
//Start thread
t.Start();
}
if ((count+1)<5)
{button5.Text ="Start Thread " + ((count+1)) ;}
else
{
button5.Text ="All Threads Started";
button5.Enabled =false;
}
}
private void StartThread()
{
//create instance form to show repation of thread
Form2 frm=new Form2();
frm.Show ();
int localCopy=count;
int WR=0;
string sW="";
//run always
while(true)
{
WR++;
sW=WR.ToString();
frm.Text="Thread " + localCopy + " (Repeat=" + sW + ")" ;
//give some break
Thread.Sleep(100);
try
{
//change back colors to show thread is running
switch (localCopy){
case 1:
if (this.button1.BackColor==Color.Red )
this.button1.BackColor=Color.Green;
else
this.button1.BackColor=Color.Red;
break;
case 2:
if (this.button2.BackColor==Color.Red )
this.button2.BackColor=Color.Green;
else
this.button2.BackColor=Color.Red;
break;
case 3:
if (this.button3.BackColor==Color.Red )
this.button3.BackColor=Color.Green;
else
this.button3.BackColor=Color.Red;
break;
case 4:
if (this.button4.BackColor==Color.Red )
this.button4.BackColor=Color.Green;
else
this.button4.BackColor=Color.Red;
break;
}
}
catch(Exception e1)
{
Console.WriteLine("Exception Form1 loop >> "+e1);
break;
}
}
}
}
}
Form2.cs
This form shows the no of time for which a single process is repeating.