using System;
using System.Threading;
using System.Windows.Forms;
namespace _04_线程执行带参数的方法
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnThreadMethodParameter_Click(object sender, EventArgs e)
{
////SetThisTextValue();
////线程调用无参的方法也是2种方法
////方法(一)
//ThreadStart start = new ThreadStart(方法名);
//Thread th = new Thread(start);
////方法(二)
//Thread th = new Thread(直接方法名);
////线程调用有参(只能是object类型的参数)的2种方法
//方法(一)
ParameterizedThreadStart para = new ParameterizedThreadStart(SetThisTextValue);//有参线程有执行的有参方法
Thread th = new Thread(para);//线程实例化, 参数为委托
//方法(二)
//Thread th = new Thread(SetThisTextValue);
th.IsBackground = true;//指定为后台线程
th.Start(10000);//启动线程 并传参 何时执行该线程 由CPU调度说了算
MessageBox.Show("观察窗体标题 正在执行带参数的方法 用线程 我是执行窗体UI的主线程,UI和循环各用各的线程在执行,互不干扰");
if (MessageBox.Show("确定后 将中止新线程执行的循环方法,看标题识别中止情况...","提示",MessageBoxButtons.OKCancel) == DialogResult.OK)
{
if (th != null)
{
th.Abort();
}
}
}
private void SetThisTextValue(object obj)
{
int num = (int)obj;
for (int i = 0; i < num; i++)
{
this.Text = i.ToString();
}
}
}
}