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);
    
    }
    
  • 相关阅读:
    windows live sync, mesh, skydrive
    忘记SQL SERVER密码的解决
    处理ObjectDataSource调用中DAL层中的异常
    C#中获取应用程序路径的方法(集合)
    datatable复制一行数据到本表
    [Yii Framework] yii中如何在查询的时候使用数据库函数
    [Yii Framework] yii的路由配置
    [Yii Framework] 已经定义的命名空间常量
    [Yii Framework] yii中关于filter
    [Yii Framework] yii中如何不加载layout
  • 原文地址:https://www.cnblogs.com/lqqgis/p/12643786.html
Copyright © 2011-2022 走看看