方法一:
启用线程:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public delegate void BackGroundWorkers();
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
Thread th;
/// <summary>
/// 加载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
GetICount();
}
int i = 0;
public void GetICount()
{
i++;
this.label1.Text = i.ToString();
Thread.Sleep(1000); //暂停线程
= new Thread(new ThreadStart(GetICount));
th.IsBackground = true;
th.Start();
}
}
}
停止线程:
public void StopThread()
{
th.Abort(); //停止线程
}
方法二:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private delegate void GetInfo();
private void Form2_Load(object sender, EventArgs e)
{
GetTime();
}
private int i = 0;
/// <summary>
/// 线程执行的方法
/// </summary>
public void GetTime()
{
i++;
this.label1.Text = i.ToString();
Thread.Sleep(200);
GetInfo gets = new GetInfo(GetTime);
gets.BeginInvoke(null, null);
}
}
}
Start():启动线程;
Sleep(int):静态方法,暂停当前线程指定的毫秒数;
Abort():通常使用该方法来终止一个线程;
Suspend():该方法并不终止未完成的线程,它仅仅挂起线程,以后还可恢复;
Resume():恢复被Suspend()方法挂起的线程的执行。