zoukankan      html  css  js  c++  java
  • 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);
    
    }
    
  • 相关阅读:
    索引压缩
    拼写校正
    词典(词汇表)
    Text Relatives II
    Text Relatives
    CoreText
    Quartz2D Text
    PDF Document Creation, Viewing
    Core Graphics Layer Drawing
    Bitmap Images and Image Masks
  • 原文地址:https://www.cnblogs.com/lqqgis/p/12643786.html
Copyright © 2011-2022 走看看