一、简单线程
Thread t = null;
private void button1_Click(object sender, EventArgs e)
{
t = new Thread(AddNumber);
t.Start();
}
private void button1_Click(object sender, EventArgs e)
{
t = new Thread(AddNumber);
t.Start();
}
int number = 0;
private void AddNumber()
{
while (true)
{
number++;
this.listBox1.Items.Add(number);
Thread.Sleep(300);
}
}
其他线程方法://挂起线程 t.Suspend();//唤醒线程 t.Resume();//线程休眠Thread.Sleep(5000); //释放线程t.Abort();
而在实际应用中大多情况下是在循环内部开辟线程:比如窗体假死等问题
二、一般线程使用,实现异步(可解决窗体假死等问题)
比如根据DataTable里面的莫个值进行操作
private void FUN()
{
{
DataTable dt = groupbll.GetGroup();
if (dt != null && dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
{
for (int i = 0; i < dt.Rows.Count; i++)
{
//带参数的线程
ThreadStart ts = new ThreadStart(MyMessage);
ParameterizedThreadStart parthread = new ParameterizedThreadStart(MyMessage);
Thread thread = new Thread(parthread);
Thread thread = new Thread(parthread);
//传递参数
myobj obj = new myobj();//myobj 为一个实体对象
obj.ID= dt.Rows[i]["ID"].ToString();
thread.Start(obj);
}
}
}
private void MyMessage(object obj1)
{
myobj obj = (myobj)obj1;
{
myobj obj = (myobj)obj1;
.....执行一系列操作
}
这样的做法可以实现一般的线程操作。用法简单,但是有其不足之处,需要开辟多个线程,如果循环次数大,可能导致线程池满等问题。四为另外的处理办法。
如果在线程中更改窗Form中控件的属性(比如在MyMessage中this.textBox1.AppendText("asdasd"))可在窗体加载事件中加入:
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
三、判断线程执行完毕
由于线程并不会一个一个按循环顺序执行,更有可能是多个一起执行,这正是线程的优点。所以不能在循环结束后判断。我采用的是Join()方法:
在上述FUN()方法基础上
ArrayList list = new ArrayList();
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
//...
list.Add(thread);
}
for (int i = 0; i < list.Count; i++)
{
Thread t = (Thread)list[i];
t.Join();
if (i + 1 == list.Count)
{
//MessageBox.Show("aaa");
this.textBox1.AppendText(" 全部执行完毕!");
}
}
{
Thread t = (Thread)list[i];
t.Join();
if (i + 1 == list.Count)
{
//MessageBox.Show("aaa");
this.textBox1.AppendText(" 全部执行完毕!");
}
}
join是阻塞调用线程,直到该线程结束后,调用线程才能继续执行。
四、使用代理的方式处理线程
以界面文本框为例,需要起单独的线程,这是我给的样例。
1. 定义事件委托
private delegate void sychflesh(int i);
2. 起一个线程
Thread thread = new Thread(DoWork);
thread.Start();
thread.Start();
public void DoWork()
{
for (int i = 0; i < 10000; i++)
{
ThreadFunction(i);
}
}
{
for (int i = 0; i < 10000; i++)
{
ThreadFunction(i);
}
}
private void ThreadFunction(int i)
{
if (this.textBox1.InvokeRequired)//等待异步
{
sychflesh flesh = new sychflesh(ThreadFunction);
this.Invoke(flesh, i);//通过代理调用刷新方法
}
else
{
textBox1.Text += i.ToString();
}
}
{
if (this.textBox1.InvokeRequired)//等待异步
{
sychflesh flesh = new sychflesh(ThreadFunction);
this.Invoke(flesh, i);//通过代理调用刷新方法
}
else
{
textBox1.Text += i.ToString();
}
}
本文为个人总结,如有更好处理办法或不足之处,希望评论。