打赏

带参数的多线程的方式

https://www.cnblogs.com/zeroone/archive/2013/09/04/3300274.html

#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() + "毫秒"); }
posted @ 2018-05-29 13:52  刘奇云  阅读(1469)  评论(0编辑  收藏  举报