码迷,mamicode.com
首页 > 编程语言 > 详细

带参数的多线程的方式

时间:2014-10-24 18:50:31      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   os   ar   for   sp   div   on   

本文来自:http://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() + "毫秒");
        }



方式一: 定义一个类,将要传的参数设置为类的属性,然后将参数值赋值给类的属性,将类作为一个参数进行传达,以下代码通过两个参数示例,多个参数一样,代码如下

bubuko.com,布布扣
bubuko.com,布布扣
    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() + "毫秒");
        }
bubuko.com,布布扣
bubuko.com,布布扣

方式二: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() + "毫秒"); }
 
 
标签: C#多线程

带参数的多线程的方式

标签:blog   http   io   os   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/zhouyunbaosujina/p/4048837.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!