【C#】线程传递参数

 


一、无参数线程的创建

 

Thread thread = new Thread(new ThreadStart(getpic));
thread.Start();
private void showmessage()
{
      Console.WriteLine("hello world");
}

 

 

二、1个参数线程的创建

Thread thread = new Thread(new ParameterizedThreadStart(showmessage));
string o = "hello";
thread.Start((object)o);
private static void showmessage(object message)
{
    string temp = (string)message;
    Console.WriteLine(message);
}

注意传递的参数只能是object类型,不过可以进行强制类型转换。

 

三、多个参数线程的创建

复制代码
public class ThreadTest
{
private string str1;
private string str2;
public ThreadTest(string a, string b)
{
str1 = a;
str2 = b;
}
public void ThreadProc()
{
Console.WriteLine(str1 + str2);
}
}
public class Example {
public static void Main() 
{
ThreadTest tt = new ThreadTest("hello ", "world");
Thread thread = new Thread(new ThreadStart(tt.ThreadProc));
thread.Start();
}
}
复制代码

将线程执行的方法和参数都封装到一个类里边,通过实例化该类,方法就可以调用属性来传递参数。

posted @   不溯流光  阅读(142)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示