ThreadStart:
ThreadStart委托定义为public delegate void ThreadStart(),所以执行的方法不能带有参数。
private void btnThreadStart_Click(object sender, EventArgs e){ Thread th = new Thread(new ThreadStart(this.ShowMsgByThreadStart)); th.Start();}private void ShowMsgByThreadStart(){ MessageBox.Show("通过ThreadStart显示消息!");}
这里我们定义了一个ThreadStart类型的委托,这个委托指定了线程需要执行的方法ShowMsgByThreadStart,在这个方法实现了一个简单的弹出消息的功能,这就是最简单的多线程的例子,在很多情况下这就足够用了。
ParameterizedThreadStart:
ParameterizedThreadStart委托定义为public delegate void ParameterizedThreadStart(object obj),所以执行的方法可以传递一个object参数。
private void btnParameterizedThreadStart_Click(object sender, EventArgs e){ Thread th = new Thread(new ParameterizedThreadStart(this.ShowMsgByParameterizedThreadStart)); th.Start("通过ParameterizedThreadStart传递参数显示消息!");}private void ShowMsgByParameterizedThreadStart(object obj){ MessageBox.Show(obj.ToString());}
上述例子中的ShowMsgByParameterizedThreadStart方法有一个object参数,通过线程委托ParameterizedThreadStart来传递参数实现显示消息的功能,虽然上述例子中只能传递一个参数,但是参数为object类型,我们可以变相的实现多个参数的传递,注意在使用object参数时需要进行类型转换,例子如下:
public class AddParams{ public int a, b; public AddParams(int num1, int num2) { a = num1; b = num2; }}private void btnMoreParas_Click(object sender, EventArgs e){ AddParams ap = new AddParams(10, 20); Thread th = new Thread(new ParameterizedThreadStart(this.MoreParameters)); th.Start(ap);}private void MoreParameters(object obj){ if (obj is AddParams) { AddParams ap = obj as AddParams; MessageBox.Show(string.Format("{0} + {1} = {2}", ap.a, ap.b, ap.a + ap.b)); }}