• C# 线程 传递参数


    方法1:使用ParameterizedThreadStart委托
    如果使用了ParameterizedThreadStart委托,线程能传递且只能传递一个object类型的参数,且返回类型为void.

    static void Main(string[] args)
    {
        string hello = "hello world";
        Thread thread = new Thread(new ParameterizedThreadStart(ThreadMainWithParameters));
        //Thread thread = new Thread(ThreadMainWithParameters); // 上面的简写
        thread.Start(hello);
        Console.Read();
    }
    
    static void ThreadMainWithParameters(object obj)
    {
        string str = obj as string;
        if (!string.IsNullOrEmpty(str))
            Console.WriteLine("Running in a thread,received: {0}", str);
    }
    

    方法2:创建自定义类
    定义一个类,在其中定义需要的字段,将线程的方法定义为类的一个实例方法.
    这种方法稍有繁琐,如果又需要,可以使用

    static void Main(string[] args)
    {
        CustomClass customClass = new CustomClass("hello world");
        Thread thread = new Thread(customClass.RunMethod);
        thread.Start();
        Console.Read();
    }
    
    public class CustomClass
    {
        private string data;
        public CustomClass(string data)
        {
            this.data = data;
        }
        public void RunMethod()
        {
            Console.WriteLine("Type2: Running in a thread,data: {0}", data);
        }
    }
    

    方法3:使用lambda表达式
    对于lambda表达式可以查看微软MSDN上的说明文档。
    在多数使用委托的时候,我们一般也可以用lambda表达式,此方法简便推荐使用。

    static void Main(string[] args)
    {
        string hello = "hello world";
        //Thread thread = new Thread(ThreadMainWithParameters(hello)) // 该形式编译报错
        Thread thread = new Thread(() => ThreadMainWithParameters(hello));
        thread.Start();
        Console.Read();
    }
    
    static void ThreadMainWithParameters(object obj)
    {
        string str = obj as string;
        if (!string.IsNullOrEmpty(str))
            Console.WriteLine("Type3: Running in a thread,received: {0}", str);
    }
    

    方法4:使用delegate委托

    static void Main(string[] args)
    {
        string hello = "hello world";
        Thread thread = new Thread(delegate() { ThreadMainWithParameters(hello); });
        thread.Start();
        Console.Read();
    }
    
    static void ThreadMainWithParameters(object obj)
    {
        string str = obj as string;
        if (!string.IsNullOrEmpty(str))
            Console.WriteLine("Type4: Running in a thread,received: {0}", str);
    
    }
    
  • 相关阅读:
    BZOJ 1305 dance跳舞(最大流+二分答案)
    计蒜客 贝壳找房计数比赛(可重全排列+逆元)
    计蒜客 贝壳找房函数最值(好题,巧妙排序)
    Codeforces 463D Gargari and Permutations(求k个序列的LCS)
    Codeforces 552C Vanya and Scales(进制转换+思维)
    Codeforces 682C Alyona and the Tree (树上DFS+DP)
    Codeforces 332B Maximum Absurdity(DP+前缀和处理)
    Codeforces 981D Bookshelves(按位贪心+二维DP)
    Codeforces 225C Barcode(矩阵上DP)
    Codeforces 988F Rain and Umbrellas(DP)
  • 原文地址:https://www.cnblogs.com/lqqgis/p/12643786.html
Copyright © 2020-2023  润新知