给线程传参数的三种方法

方式一:使用ParameterizedThreadStart委托

如果使用了ParameterizedThreadStart委托,线程的入口必须有一个object类型的参数,且返回类型为void。

using System;usingSystem.Threading;namespace ThreadWithParameters{
    class Program
    {
        staticvoid Main(string[]args)
        {
            string hello = "helloworld"; 
           //这里也可简写成Thread thread = new Thread(ThreadMainWithParameters);
            //但是为了让大家知道这里用的是ParameterizedThreadStart委托,就没有简写了
            Threadthread = new Thread(new ParameterizedThreadStart(ThreadMainWithParameters));
            thread.Start(hello);
            Console.Read();
        }
        static void ThreadMainWithParameters(objectobj) 
       {
            stringstr = obj as string;
            if(!string.IsNullOrEmpty(str))
                Console.WriteLine("Runningin a thread,received: {0}", str);
        }
    }
}

这里稍微有点麻烦的就是ThreadMainWithParameters方法里的参数必须是object类型的,我们需要进行类型转换。为什么参数必须是object类型呢,各位看看ParameterizedThreadStart委托的声明就知道了。
 

 public delegate void ParameterizedThreadStart(object obj);//ParameterizedThreadStart委托的声明

 方式二:创建自定义类

  定义一个类,在其中定义需要的字段,将线程的主方法定义为类的一个实例方法,说得不是很明白,还是看实际的例子吧。
  

using System;usingSystem.Threading;namespace ThreadWithParameters{
    publicclass MyThread
    {
        privatestring data;
        publicMyThread(string data)
        {
            this.data = data;
        }
        publicvoid ThreadMain()
        {
            Console.WriteLine("Running in a thread,data: {0}", data);
        }
    }
    class Program
    {
        staticvoid Main(string[] args)
        {
            MyThreadmyThread = new MyThread("hello world");
            Threadthread = new Thread(myThread.ThreadMain);
            thread.Start();
            Console.Read();
        }
    }
}

方式三:利用lambda表达式

using System;usingSystem.Threading;namespaceThreadWithParameters{    classProgram
    { 
       staticvoid Main(string[]args)
        {
            string hello = "helloworld"; 
           //如果写成Thread thread = new Thread(ThreadMainWithParameters(hello));这种形式,编译时就会报错
            Threadthread = new Thread(() => ThreadMainWithParameters(hello));
            thread.Start();
            Console.Read();
        }
        static voidThreadMainWithParameters(string str) 
       { 
           Console.WriteLine("Running in a thread,received: {0}", str); 
       }
    }
}

评价

第三种方法最好,简单明了。但是在跨线程调用时,如果给方法传递的是窗体控件的信息时,第一种方法比较简单,比如:

           Threadthread = new Thread(new ParameterizedThreadStart(ThreadMainWithParameters));
            thread.Start(textBox1.Text);

posted on 2017-09-23 09:55  五月槐花  阅读(668)  评论(0编辑  收藏  举报

导航