异步线程






1.16/5 (23投票s)
2004年4月20日

65994

1198
使用 C# 进行异步线程。
引言
这段代码演示了如何使用 .net 线程轻松创建异步进程。
为什么使用异步线程
假设你有一堆需要保存数据的请求,那么你需要使用线程。
否则,系统将等待第一个请求完成,然后唤醒函数处理第二个请求。
通过使用线程,将始终创建函数的新的实例,并且许多实例将一起运行,并且数据将从应用程序端并行保存。
你需要做什么
创建一个将被快速调用的函数。
假设
void
SaveUser(int id,string name){...}
现在创建一个将创建线程并将此函数添加到其中的函数...
void dosave(id,name){
t=new Thread (new
ThreadStart(SaveUser(id,name)));
}
在每次保存数据请求时调用上面的函数...
dosave(1,"jhon smith");
要使用线程需要包含什么
你需要包含线程命名空间才能使用线程类。
usingSystem.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.