前言
通常会有需求通过多线程调用带参数的委托函数,有一个参数的,也有多个参数的,下面来讲讲实现的方式
执行带一个参数的委托函数
#region 执行带一个参数的多线程 Thread mythread = new Thread(new ParameterizedThreadStart(Calculate)); mythread.IsBackground = true; mythread.Start(500); #endregion private void Calculate(object Max) //带一个参数的委托函数 { int max = (int)Max; Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = 0; i < max; i++) { Thread.Sleep(5); } stopwatch.Stop(); long lSearchTime = stopwatch.ElapsedMilliseconds; MessageBox.Show(lSearchTime.ToString() + "毫秒"); }
执行带多个参数的委托函数
方式一: 定义一个类,将要传的参数设置为类的属性,然后将参数值赋值给类的属性,将类作为一个参数进行传达,以下代码通过两个参数示例,多个参数一样,代码如下
class MyClass { public int Max { get; set; } public int Min { get; set; } } #region 第一种方式:执行带多个参数的多线程 MyClass model = new MyClass(); model.Max = 500; model.Min = 0; Thread mythread1 = new Thread(new ParameterizedThreadStart(CalculateTwo)); mythread1.IsBackground = true; mythread1.Start(model); #endregion private void CalculateTwo(object Myclass) //带多个参数的委托函数 { MyClass model = (MyClass)Myclass; Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = model.Min; i < model.Max; i++) { Thread.Sleep(5); } stopwatch.Stop(); long lSearchTime = stopwatch.ElapsedMilliseconds; MessageBox.Show(lSearchTime.ToString() + "毫秒"); }
方式二:lambda表达式的方式,简单方便,代码如下:
#region 第二种方式:执行带多个参数的多线程 Thread mythread2 = new Thread(() => CalculateThree(500, 0)); mythread2.IsBackground = true; //設置為後臺線程,程式關閉后進程也關閉,如果不設置true,則程式關閉,此線程還在內存,不會關閉 mythread2.Start(); #endregion private void CalculateThree(int Max,int Min) //带多个参数的委托函数 { Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = Min; i < Max; i++) { Thread.Sleep(5); } stopwatch.Stop(); long lSearchTime = stopwatch.ElapsedMilliseconds; MessageBox.Show(lSearchTime.ToString() + "毫秒"); }
结束语
以上就是执行带参数的多线程的几种方式,各位看官是否还有更好的方式??