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);

}
posted @   lqqgis  阅读(362)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示