线程的创建
线程是使用Thread 类来处理的,包含在System.Threading 中。通过实例化一个Thread对象来创建一个线程。Thread类接受一
- Thread t=new Thread(new ThreadStart(TestMethod));
- t.Start();
个ThreadStart委托,或ParameterizedThreadStart委托的构造函数,
- Thead th = new Thread(new ParameterizedThreadStart(TestMethod));
- th.Start();
Thread 类常用属性
1 IsAlive 获取一个只,该值指示当前线程的执行状态
2 Priority 获取或设置,线程优先级
3 IsBackgroud 获取或设置,是否为后台线程
4 CurrentThread 获取当前正在运行的线程
常用方法
Abort() :终止线程
Start() 开始线程
例子
下面的例子可以体现出线程的意义,写了一个窗体,每隔0.5秒刷新一下label中的值,从1 一直加下去
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Threading;//调用多线程要using这个~
-
- namespace WindowsFormsApplication1
- {
- public partial class Form1 : Form
- {
- Thread _thread = null;//定义线程
- delegate void SetLabelText(string str);//定义委托,用来完成线程的赋值
-
- public Form1()
- {
- InitializeComponent();
- }
- /// <summary>
- /// 作为线程,不断地变换label中的值
- /// </summary>
- private void setNum()
- {
- for (int i = 1; i < 100; ++i)
- {
- //这么调用会失败,产生错误“线程间操作无效”
- //this.label1.Text = i.ToString();
-
- //需要用委托调用
- SetLabelText st = new SetLabelText(setLabel);
- //用invoke 方法来达到线程间操作的目的
- this.Invoke(st, i.ToString());
- Thread.Sleep(500);
- }
- }
- /// <summary>
- /// 加载窗体,开始线程
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Form1_Load(object sender, EventArgs e)
- {
- _thread = new Thread(new ThreadStart(setNum));
- _thread.Start();
- }
-
- /// <summary>
- /// 窗体关闭,要结束线程
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Form1_FormClosed(object sender, FormClosedEventArgs e)
- {
- if (_thread.IsAlive)
- {
- _thread.Abort();
-
- }
- }
- /// <summary>
- /// 为label 赋值
- /// </summary>
- /// <param name="str"></param>
- private void setLabel(string str)
- {
- this.label1.Text = str;
- }
- }
- }
要注意的是线程间的操作时需要调用委托的,上面的例子如果setNum这样写就会出错
- private void setNum()
- {
- for (int i = 1; i < 100; ++i)
- {
- //这么调用会失败,产生错误“线程间操作无效”
- this.label1.Text = i.ToString();
-
- //需要用委托调用
- //SetLabelText st = new SetLabelText(setLabel);
- //用invoke 方法来达到线程间操作的目的
- // this.Invoke(st, i.ToString());
- Thread.Sleep(500);
- }
- }
|