zoukankan      html  css  js  c++  java
  • 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());
    }
    }
    }


     
     
    注:此文章转载至白衣轩

  • 相关阅读:
    Permission denied (publickey). fatal: Could not read from remote repository.
    jQuery OCUpload一键上传文件
    org.apache.subversion.javahl.ClientException: Working copy is not up-to-date
    测开之路一百三十五:实现登录身份验证功能
    测开之路一百三十四:实现指定查找功能
    测开之路一百三十三:实现sql函数封装
    测开之路一百三十二:实现修改功能
    测开之路一百三十一:实现删除功能
    测开之路一百三十:实现前端到数据库交互(增和查)
    测开之路一百二十九:jinja2模板语法
  • 原文地址:https://www.cnblogs.com/hailexuexi/p/1903575.html
Copyright © 2011-2022 走看看