C# 线程调用带参数的方法

示例1:以类实现 

       class Program

      { 

        static void Main(string[] args)

        {

            Test test = new Test("线程调用带参数的方法", "轻松搞定");

            Thread thread = new Thread(new ThreadStart(test.Write));

            thread.Start();

        }

    }

    public class Test

    {

        private string p1;

        private string p2;

        public Test(string par1,string par2)

        {

            p1 = par1;

            p2 = par2;

        }

        public void Write()

        {

            Console.WriteLine(p1);

            Console.WriteLine(p2);

        }

}

  

示例2:使用ParameterizedThreadStart //只能带一个object的参数 

class Program

    {

        static void Main(string[] args)

        {

            Program pro=new Program();

            Thread thread = new Thread(new ParameterizedThreadStart(pro.Write2));

            thread.Start("线程调用带参数的方法");

        }

        public void Write2(object par)

        {

            Console.WriteLine(par);

 

        }

}

示例3:使用静态变量,属性 //慎用

static void Main(string[] args)

        {

            Program pro=new Program();

            Thread thread = new Thread(new ThreadStart(pro.Write3));

            thread.Start();

        }

        public void Write3()

        {

            Console.WriteLine(Par);

        }

public static string Par

        {

            get

            {

                return "线程调用带参数的方法";

            }

        }

 

 

class Program
{
//定义一个多参数的委托
private delegate void SayHello(params object[] obj);
private static Test test = new Test();
//把委托的方法指针指向Test类的Say方法
private static SayHello say = new SayHello(test.Say);
static void Main(string[] args)
{
//线程调用代理方法
Thread newThread = new Thread(new ThreadStart(Execute));
newThread.Start();
}

static void Execute()
{
//给Say方法传参
say("Hi", " ", "I'm", " ", "Bob");
}
}
class Test
{
public void Say(params object[] obj)
{
foreach (object o in obj)
{
Console.Write(o.ToString());
}
}
}


 

 
 
注:此文章转载至白衣轩

posted @ 2010-12-12 09:44  海乐学习  阅读(710)  评论(0编辑  收藏  举报