• 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());
    }
    }
    }


     
     
    注:此文章转载至白衣轩

  • 相关阅读:
    一生不可错过的五句话
    分布式缓存系统Memcached简介与实践[转]
    telnet serverip serverport 可以测试服务器端口是否通
    使用c#生成高品质小空间的缩略图
    sql server2005对tsql的增强之在聚合函数的后面使用over关键字
    (转)让你受益终身的10个Word实用技巧
    sql取所有记录中每天的最后一笔交易的记录
    屏蔽服务器端包含在文件不存在时报错的错误信息
    c#农历日历类
    Niubility 英语教程
  • 原文地址:https://www.cnblogs.com/hailexuexi/p/1903575.html
Copyright © 2020-2023  润新知