使用多线程的步骤:
1、引用命名空间:using System.Threading;
2、编写好需要多线程执行的方法;
3、声明一个线程并传入一个需要执行方法;
4、调用线程的Start()方法标志可以执行;
具体代码如下:
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;
//引用Threading命名空间
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//关闭对文本框的跨线程操作检查
TextBox.CheckForIllegalCrossThreadCalls = false;
}
//------------------------无参方法--------------------------
/// <summary>
/// 一个无参方法
/// </summary>
private static void CountTime()
{
DateTime beginTime = DateTime.Now;
for (long i = 0; i < 9999999999; i++)
{
}
TimeSpan ts = beginTime.Subtract(DateTime.Now);
MessageBox.Show("循环完毕~~~"+ts.TotalMilliseconds);
}
/// <summary>
/// 执行无参方法的线程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
//声明一个线程并传入一个方法
Thread threadFirst = new Thread(CountTime);
//当窗体关闭时,线程也关闭
threadFirst.IsBackground = true;
//开始执行
threadFirst.Start();
}
//------------------------方法重入问题--------------------------
/// <summary>
/// 修改文本框中的内容
/// </summary>
void ChangeText()
{
for (int i = 0; i < 1000; i++)
{
int a = int.Parse(textBox1.Text);
Console.WriteLine(Thread.CurrentThread.Name + ",a=" + a);
a++;
textBox1.Text = a.ToString();
}
}
/// <summary>
/// 方法重入问题
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
Thread th = new Thread(ChangeText);
//给线程命名
th.Name = "t";
th.IsBackground = true;
th.Start();
Thread th1 = new Thread(ChangeText);
//给线程命名
th1.Name = "t1";
th1.IsBackground = true;
th1.Start();
}
//------------------------带一个参的方法--------------------------
void ShowTxtName(object name)
{
if (name != null)
{
MessageBox.Show("name=" + name.ToString());
}
else
{
MessageBox.Show("null");
}
}
/// <summary>
/// 执行带一个参数的线程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
Thread th = new Thread(ShowTxtName);
th.IsBackground = true;
th.Start(txtName.Text);
}
//------------------------带多个参的方法--------------------------
/// <summary>
/// 带多个参的方法
/// </summary>
/// <param name="li"></param>
void ShowTxtNameList(object li)
{
List<string> list = li as List<string>;
if (list!=null)
{
foreach (string item in list)
{
MessageBox.Show(item);
}
}
}
/// <summary>
/// 执行带多个参数的线程
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
Thread th = new Thread(ShowTxtNameList);
th.IsBackground = true;
//使用多个参数时,只能用List集合
th.Start(new List<string> { "aa","bb","cc"});
}
}
}